Member-only story
TypeScript Tidbits
This article is about TypeScript. It’s not specifically about Angular, NgRx, React or redux-observable; it’s about what I learned — the hard way — when I built ts-action
.
Literal types: widening and narrowing
TypeScript has the concept of string, numeric, boolean and enum literal types. Variables having a literal type may only be assigned the specified literal value. For example, this variable has a literal type:
let foo: "FOO";
And can only be assigned a value of "FOO"
:
foo = "FOO"; // OK
foo = "BAR"; // Type '"BAR"' is not assignable to type '"FOO"'.
When a literal or a variable that has a literal type is assigned to a constant, a literal type is inferred — the inference is safe, as the constant’s value cannot be changed. Here, foo
will be inferred to be of type "FOO"
:
const foo = "FOO";
When a constant or variable with a literal type is assigned to a variable, the literal type cannot be inferred, as the variable’s value could be changed after the assignment. In these situations, the inference is widened:
const foo = "FOO"; // Inferred to be "FOO".
let val = foo; // Inferred to be string.