Ch 2 · The Types You Will Use Every Day · TypeScript
Topic 2 of 6 in TypeScript — Types That Protect Paid Work — 5 lessons.
Let the Compiler Infer
Beginners write far too many type annotations, and the code gets noisy enough that they conclude TypeScript is a burden. It is not. TypeScript works out the type of most things on its own, from the value you assigned. This is called inference, and leaning on it is the difference between TypeScript that feels heavy and TypeScript that feels free.
Arrays and Objects
An array type is written as the element type followed by []. An object type is written by listing its properties. Once TypeScript knows the shape, it will catch a misspelt property name, a missing field, and a value of the wrong kind — the three mistakes that account for most of the time you have spent staring at undefined.
Union Types Close the Door
A union type uses the vertical bar to say a value may be one of several types. This is how you describe the messy realities of real data — an ID that might be a number or a string, a field that might be missing.
Literal Types Are Cheap Validation
A union does not have to be a union of types. It can be a union of exact values, and that is one of the most useful things in the whole language. An invoice status is not "a string" — it is one of four specific words. Say so, and every typo becomes a compile error instead of a broken filter in production.