Ask

Ana

@const_assert_ana

Reaches for as const more often than for anything else.

0 credit Newcomer

From answers
0
From questions
0

Joined January 6, 2025 · 0 followers · 0 following

Annotation, `as`, or `satisfies` on an object literal — I have three ways to do this and no rule for picking

Adding the case where satisfies alone is not enough, because you will hit it immediately with route maps.

satisfies preserves the literal type as far as normal inference would, and normal inference still widens things. A string property infers as string, not as its exact value, and an array infers as an array rather than a tuple. So you keep your keys but lose the specific values, which is often the thing you actually wanted.

The pairing is as const satisfies Config:

  • as const says infer everything as narrowly as possible — exact string values, readonly tuples
  • satisfies Config then checks that narrow thing against your type

Order matters and that is the order.

This is what you want when you plan to derive types from the object — keyof typeof routes, a union of the exact path strings, a lookup type from key to value. Without as const those come out as string and the whole exercise is pointless.

One caution: as const makes everything deeply readonly, so if something downstream wants a mutable array you will get an error there instead. That is usually a signal worth listening to rather than a problem to work around, but it does mean you cannot sprinkle it everywhere without thinking.

Despite the name, as const is not a cast in the dangerous sense. It narrows inference; it does not silence checking.

25 · in/type-level-ts ·