Basic Types
- stringText values
- numberNumeric values
- booleantrue/false
- null / undefinedAbsence
- anyOpt-out typing
- unknownType-safe any
- neverNever returns
- voidNo return value
Utility Types
- Partial<T>All optional
- Required<T>All required
- Readonly<T>Immutable
- Pick<T, K>Select props
- Omit<T, K>Exclude props
- Record<K, V>Key-value map
- ReturnType<T>Func return type
Array & Tuple
- string[]String array
- Array<string>Generic array
- [string, number]Tuple type
- readonly string[]Immutable array
Type Operators
- keyof TObject keys
- typeof xType from value
- T | UUnion type
- T & UIntersection
- T extends UConstraint
- inferInfer in conditional
Interfaces & Types
// Interface
interface User {
id: number;
name: string;
email?: string; // Optional
readonly createdAt: Date;
}
// Type alias
type ID = string | number;
type Status = 'pending' | 'active' | 'completed';
// Extending interfaces
interface Admin extends User {
role: 'admin';
permissions: string[];
}
Generics
// Generic function
function identity<T>(arg: T): T {
return arg;
}
// Generic interface
interface ApiResponse<T> {
data: T;
status: number;
message: string;
}
// Generic with constraint
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Type Guards
// typeof guard
if (typeof x === 'string') {}
// instanceof guard
if (x instanceof Date) {}
// Custom type guard
function isUser(x: any): x is User {
return x.name !== undefined;
}
// in operator
if ('name' in obj) {}
tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true
},
"include": ["src/**/*"]
}
Conditional & Mapped Types
// Conditional type
type NonNullable<T> = T extends null | undefined ? never : T;
// Mapped type
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
// Template literal type
type EventName = `on${Capitalize<string>}`;
// Extract from union
type StringOnly = Extract<string | number | boolean, string>;
Assertion & Cast
- x as TypeType assertion
- x!Non-null assert
- x as constLiteral type
- satisfiesType checking
Function Types
// Function type
type Callback = (x: number) => void;
// Function overloads
function parse(x: string): number;
function parse(x: number): string;
function parse(x: any) {
return typeof x === 'string'
? parseInt(x) : x.toString();
}