Basic types
let s: string; let n: number; let b: boolean;
let arr: number[] = []; let tup: [string, number];
let u: unknown; // must narrow before use (safe any)
let a: any; // opts out of checking
function fail(): never { throw new Error(); }
function log(): void {}type vs interface
interface | type | |
|---|---|---|
| Object shapes | yes | yes |
| Unions / primitives / tuples | no | yes |
| Declaration merging | yes | no |
extends | extends | & intersection |
Rule of thumb: interface for public object contracts, type for unions and compositions.
Unions & narrowing
type Result = { ok: true; data: User } | { ok: false; error: string };
function handle(r: Result) {
if (r.ok) r.data; // narrowed by discriminant
else r.error;
}
typeof x === 'string'; x instanceof Date; 'key' in obj;
function isUser(x: unknown): x is User { // type guard
return typeof x === 'object' && x !== null && 'id' in x;
}Exhaustiveness check
function area(s: Shape) {
switch (s.kind) {
case 'circle': return Math.PI * s.r ** 2;
case 'square': return s.side ** 2;
default: { const _x: never = s; return _x; } // error if a case is missing
}
}Generics
function first<T>(xs: T[]): T | undefined { return xs[0]; }
function prop<T, K extends keyof T>(o: T, k: K): T[K] { return o[k]; }
interface ApiResponse<T = unknown> { data: T; status: number }Utility types
| Type | Does |
|---|---|
Partial<T> / Required<T> | all props optional / required |
Readonly<T> | all props readonly |
Pick<T, K> / Omit<T, K> | keep / drop keys |
Record<K, V> | object with keys K |
Exclude<U, X> / Extract<U, X> | filter a union |
NonNullable<T> | drop null / undefined |
ReturnType<F> / Parameters<F> | from a function type |
Awaited<P> | unwrap a Promise |
Mapped & conditional types
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
type ElementOf<T> = T extends (infer U)[] ? U : never;
type IsString<T> = T extends string ? true : false;Useful operators
const cfg = { env: 'prod', port: 80 } as const; // literal + readonly
type Env = typeof cfg['env']; // 'prod'
type Keys = keyof typeof cfg; // 'env' | 'port'
const c = { port: 80 } satisfies Partial<Config>; // check without widening
el!.focus(); // non-null assertion (avoid if possible)tsconfig essentials
{
"compilerOptions": {
"strict": true,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noUncheckedIndexedAccess": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist"
}
}strict enables strictNullChecks, noImplicitAny, strictFunctionTypes and more.
Common interview Qs
- any vs unknown:
unknownforces narrowing before use,anydisables checks. - Structural typing: compatibility is by shape, not by name.
- Enums: prefer union of string literals or
as constobjects; enums emit runtime code. - Types are erased at runtime: validate external input with zod/io-ts.