DAY 11 OF 30
Literal types
Yesterday, in one sentence
TypeScript compares types by their shape rather than their name. If a value has the properties a type requires, it is compatible with that type.
Did you say:
- ✓types are compared by shape, not name
- ✓having the required properties is enough
Interview question
type A = X & Y and interface A extends X, Y produce the same type. Why?Because TypeScript compares types by their shape. Both produce an object type
with everything from X and Y, and the compiler does not care which keyword
built it.
Did you say:
- ✓both combine the same properties
- ✓TypeScript compares shape, not how the type was declared
A literal type is a type whose only allowed value is one exact value.
type Alignment = "hero";
let side: Alignment = "hero";
side = "hero"; // ok
side = "villain"; // ❌ Type '"villain"' is not assignable to type '"hero"'
Literal types are most often used in a union typeUnion Type, listing every value something is allowed to be. This is called a literal union.
type Alignment = "hero" | "villain" | "antihero";
let side: Alignment = "hero";
side = "antihero"; // ok
side = "mutant"; // ❌ Type '"mutant"' is not assignable to type 'Alignment'
string would accept any text at all, including a typo. Alignment accepts exactly
three values, and anything else is a build timeBuild Time error.
Literal types work with numbers and booleans too.
type Rank = 1 | 2 | 3;
type Recruited = true;
Check yourself
"hero", "villain" and "antihero"?A literal union lists exactly which values are allowed. string accepts any text, string[] is an array type, and c uses &, which asks for a value that is all three at once rather than one of the three.
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