Handbooks / TypeScript / Chapter 1
Basic Types
7 pages · ~5 min✓ Reviewed
Start here. Next up: Interfaces, Types and Unions.
Annotations and Inference Mental Model
1. Annotation vs Inference
- Annotation = explicit type after a colon:
let n: number = 5 - Types are erased at compile time: no runtime effect
- Inference: TS derives the type from the initializer
| Code | Type |
|---|---|
let n: number = 5 | number (explicit) |
let n = 5 | number |
const n = 5 | 5 (literal type) |
2. Where to Annotate
- Annotate parameters: never inferred from the body
- Annotate exported return types
- Let infer locals and callbacks
- Contextual typing: the array type gives
xits type
typescript
export function double(xs: number[]): number[] { return xs.map(x => x * 2); // x: number }
no annotation needed on x
3. Common Mistake
typescript
let x; // implicit any (evolving any) x = 5; // now treated as number let y: number; // fix: annotate
or initialize: let x = 5
No initializer, no type
let x; is implicitly any. Annotate it or initialize it.
Primitives, Arrays and Tuples
1. Primitives
- Lowercase only:
stringnumberbooleanbigintsymbolnullundefined - Never
String/Number: those are wrapper objects, not the primitives
2. Arrays and Tuples
| Type | Example | Rule |
|---|---|---|
number[] |
any, unknown and never
1. any vs unknown
anydisables checking: every operation compiles, errors surface at runtimeanyspreads through assignmentsunknown= safe top type: anything goes in- Narrow first:
typeof,instanceof, type guard
| any | unknown | |
|---|---|---|
| Assign to it |
void and Enums vs Union Literals
1. void, undefined, never
| Type | Means |
|---|---|
void | result ignored |
undefined | result is the value undefined |
never | never returns at all |
- Callback typed
() => voidmay return a value, ignored - Function declared
: voidcannot return one
Strict Mode and Common Mistakes
1. What strict turns on
"strict": truein tsconfig enables the whole family- noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization
- noImplicitThis, alwaysStrict, useUnknownInCatchVariables, strictBuiltinIteratorReturn (TS 5.6+)
2. The big three
| Flag | Error when | Fix |
|---|---|---|
| strictNullChecks |
TypeScript Types Cheat Sheet
1. Annotate and Collect
- Annotate params and exported returns:
function f(a: A): R let x: T; let locals and callbacks inferas constkeeps literals:readonly ['x', 1]
| Type | Meaning |
|---|---|
T[] | array |
readonly T[] | no push, no index assign |
Check yourself
With strict on, does let x; x = 5; x = 'hi'; compile?
- Yes:
let x;is an evolving any, so each assignment is accepted. - Fix: write
let x: number = 5;or initialize it.
What is wrong with function len(v: unknown) { return v.length; }?
- Error: an
unknownvalue cannot be used until it is narrowed. - Fix:
if (typeof v === 'string') return v.length;