DAY 12 OF 30
as const
Yesterday, in one sentence
A type whose only allowed value is one exact value, like "hero" or 6. They
are usually used in a union to list every value something can be.
Did you say:
- ✓only one exact value is allowed
- ✓usually used in a union to list every allowed value
Interview question
string?A union of literal types listing every allowed value. string accepts any text
including a typo, a literal union accepts only the values you listed.
Did you say:
- ✓a union of literal types
- ✓lists every allowed value
- ✓`string` would accept any text, including a typo
Type inferenceType Inference sets a different type depending on whether a value can be reassigned.
let hero = "xavier"; // inferred as string
const villain = "magneto"; // inferred as "magneto"
hero is a let and so can be reassigned later, which is why TypeScript infers
string. villain is a const and so cannot be reassigned, which is why TypeScript
infers the literal typeLiteral Type "magneto".
When you assign a const to an object or an array, the values inside can still be
reassigned, so TypeScript does not infer a literal type for them.
const jean = { side: "hero" }; // { side: string }
const powers = ["telepathy", "telekinesis"]; // string[]
as const tells TypeScript to infer the narrowest type it can and make everything
readonly. It applies all the way down, so nested object properties and array values
are inferred as their literal types and made readonly as well.
const jean = { side: "hero" } as const; // { readonly side: "hero" }
jean.side = "villain"; // ❌ Cannot assign to 'side', it is read-only
It does the same to an array, which also becomes a tuple typeTuple with a fixed length.
const powers = ["telepathy", "telekinesis"] as const;
// readonly ["telepathy", "telekinesis"]
powers[0] = "flight"; // ❌ Cannot assign to '0', it is read-only
Check yourself
roster?
const roster = ["Scott", "Jean"] as const
as const keeps each value as its literal type, fixes the length, and makes it readonly.
as const do in TypeScript?It tells TypeScript to infer the narrowest possible type from a value and make it readonly. Values keep their literal types, and arrays become readonly tuples.
Did you say:
- ✓infers the narrowest possible type
- ✓makes everything readonly
- ✓arrays become readonly tuples