Languages
TypeScript
Types, generics, utility types, and narrowing.
Basic types
let n: number = 1;
let s: string = "x";
let ok: boolean = true;
let arr: number[] = [1, 2];
let tup: [string, number] = ["a", 1];
let any1: unknown; // prefer over any
let n2: number | null = null;Interfaces & types
interface User {
id: number;
name: string;
role?: "admin" | "user"; // optional + union
readonly created: Date;
}
type ID = string | number;
type Point = { x: number; y: number };Functions
function add(a: number, b: number): number {
return a + b;
}
const greet = (name: string = "world"): string =>
`Hi ${name}`;
// overloads
function len(x: string): number;
function len(x: any[]): number;Generics
function first<T>(arr: T[]): T | undefined {
return arr[0];
}
interface Box<T> { value: T }
// constraints
function prop<T, K extends keyof T>(o: T, k: K) {
return o[k];
}Utility types
Partial<T>All props optionalRequired<T>All props requiredPick<T, K>Subset of keysOmit<T, K>Exclude keysRecord<K, V>Map typeReadonly<T>Immutable propsReturnType<F>Function return typeNarrowing
if (typeof x === "string") { /* string */ }
if (Array.isArray(x)) { /* array */ }
if ("id" in obj) { /* has id */ }
if (x instanceof Date) { /* Date */ }
// discriminated union
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; s: number };