Basic Types
let name: string = "Alice";
let age: number = 30;
let active: boolean = true;
let items: string[] = ["a", "b"];
let tuple: [string, number] = ["age", 30];
let anything: any = 42;
let unknown: unknown = "?"; // Safer than any
type ID = string | number; // Union type
Interfaces vs Types
// Interface — for objects, can be extended
interface User {
id: number;
name: string;
email?: string; // Optional
readonly createdAt: Date; // Immutable
}
interface Admin extends User {
role: 'admin';
}
// Type alias — for unions, intersections, primitives
type Status = 'active' | 'inactive';
type UserWithRole = User & { role: string };
type StringOrNumber = string | number;
Generics
function identity<T>(value: T): T {
return value;
}
interface ApiResponse<T> {
data: T;
error?: string;
}
// Constrained generic
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
Utility Types
| Type | Description |
Partial<T> | All properties optional |
Required<T> | All properties required |
Pick<T, K> | Select specific properties |
Omit<T, K> | Remove specific properties |
Record<K, V> | Object with typed keys/values |
Readonly<T> | All properties readonly |
ReturnType<F> | Return type of function |
Awaited<T> | Unwrap Promise type |
Type Guards
function isString(val: unknown): val is string {
return typeof val === 'string';
}
// Discriminated union
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rect'; width: number; height: number };
function area(s: Shape) {
switch (s.kind) {
case 'circle': return Math.PI * s.radius ** 2;
case 'rect': return s.width * s.height;
}
}