Examples assume TypeScript 5 with strict turned on.
Basic types
_10let id: number = 1;_10let name: string = 'Ann';_10let tags: string[] = [];_10let pair: [string, number] = ['a', 1];_10let anything: unknown; // safer than any_10function log(msg: string): void {}
Types and interfaces
_10type Id = string | number; // union_10type Point = { x: number; y: number };_10interface User {_10 id: Id;_10 name: string;_10 email?: string; // optional_10 readonly createdAt: Date;_10}_10interface Admin extends User { role: 'admin' }
Literal types
_10type Status = 'idle' | 'loading' | 'done';_10const sizes = ['sm', 'md', 'lg'] as const;_10type Size = (typeof sizes)[number]; // 'sm' | ...
Generics
_10function first<T>(list: T[]): T | undefined {_10 return list[0];_10}_10type ApiResult<T> = { data: T; error?: string };_10function byId<T extends { id: string }>(xs: T[]) {}
Utility types
_10Partial<User> // every key optional_10Required<User> // every key required_10Pick<User, 'id'> // only these keys_10Omit<User, 'email'> // all but these keys_10Record<string, User> // object map_10ReturnType<typeof fn> // what fn returns_10Awaited<Promise<T>> // T_10NonNullable<T | null> // T
Narrowing
_10if (typeof id === 'string') id.toUpperCase();_10if ('role' in user) user.role;_10if (err instanceof Error) err.message;_10_10function isUser(x: unknown): x is User {_10 return typeof x === 'object' && x !== null_10 && 'id' in x;_10}
Exhaustive checks
_11function label(s: Status) {_11 switch (s) {_11 case 'idle': return 'Waiting';_11 case 'loading': return 'Loading';_11 case 'done': return 'Done';_11 default: {_11 const never: never = s; // errors if missed_11 return never;_11 }_11 }_11}
Handy operators
_10const config = { port: 3000 } satisfies Config;_10const el = document.querySelector('a')!; // not null_10type Keys = keyof User; // 'id' | 'name' ..._10type Name = User['name']; // string
tsconfig essentials
_10{_10 "compilerOptions": {_10 "strict": true,_10 "target": "ES2022",_10 "module": "NodeNext",_10 "noUncheckedIndexedAccess": true,_10 "skipLibCheck": true_10 }_10}