📖 Guide
TypeScript Reference
Complete TypeScript reference — types, interfaces, generics, utility types, and advanced patterns.
138 commands across 12 categories
Basic TypesInterfacesType AliasesGenericsEnumsUtility TypesType GuardsMapped TypesConditional TypesDecoratorsModule SystemCommon Patterns
Basic Types
| Command | Description |
|---|---|
let x: string = "hello" | String type annotation |
let n: number = 42 | Number type (integers and floats) |
let b: boolean = true | Boolean type |
let arr: number[] = [1, 2, 3] | Array type using bracket syntax |
let arr: Array<number> = [1, 2, 3] | Array type using generic syntax |
let tuple: [string, number] = ["a", 1] | Tuple type — fixed-length array with specific types per position |
let u: undefined = undefined | Undefined type |
let n: null = null | Null type |
let a: any = "anything" | Any type — opts out of type checking (avoid when possible) |
let u: unknown = getData() | Unknown type — type-safe alternative to any, must narrow before use |
function fail(): never { throw new Error() } | Never type — function that never returns (throws or infinite loop) |
let v: void = undefined | Void type — absence of a return value |
let obj: object = { x: 1 } | Object type — any non-primitive value |
let sym: symbol = Symbol("id") | Symbol type — unique immutable identifier |
let big: bigint = 100n | BigInt type — arbitrary precision integers |
let literal: "hello" = "hello" | String literal type — exact value only |
let num: 42 = 42 | Numeric literal type |
let val: string | number | Union type — can be either type |
let val: string & { brand: true } | Intersection type — combines multiple types |
Interfaces
| Command | Description |
|---|---|
interface User { name: string; age: number } | Define an interface with required properties |
interface User { email?: string } | Optional property using ? |
interface Config { readonly apiKey: string } | Readonly property — cannot be reassigned after creation |
interface StringMap { [key: string]: string } | Index signature — allow any string key with string values |
interface Fn { (x: number): string } | Call signature — describe a callable type |
interface Ctor { new (name: string): User } | Construct signature — describe a class constructor |
interface Animal { speak(): void }
interface Dog extends Animal { breed: string } | Interface extension — inherit properties from another interface |
interface A { x: number }
interface B { y: number }
interface C extends A, B { z: number } | Multiple inheritance — extend several interfaces |
interface Box<T> { value: T } | Generic interface — parameterized by type T |
interface User { name: string }
interface User { age: number } | Declaration merging — interfaces with same name are merged automatically |
Type Aliases
| Command | Description |
|---|---|
type ID = string | number | Type alias for a union type |
type Point = { x: number; y: number } | Type alias for an object shape |
type Callback = (data: string) => void | Type alias for a function signature |
type Status = "loading" | "success" | "error" | String literal union type — like an enum but lighter |
type Pair<T> = [T, T]e.g. const p: Pair<number> = [1, 2] | Generic type alias |
type Nested = { val: number; children: Nested[] } | Recursive type alias — type references itself |
type Result<T> = { ok: true; data: T } | { ok: false; error: string } | Discriminated union — tagged union with a common discriminant |
type Keys = keyof User | keyof — get union of property names as string literals |
type Val = User["name"] | Indexed access type — get the type of a specific property |
type Ret = ReturnType<typeof fn> | Extract the return type of a function |
Generics
| Command | Description |
|---|---|
function identity<T>(arg: T): T { return arg } | Generic function — works with any type while preserving it |
function first<T>(arr: T[]): T | undefined { return arr[0] } | Generic with array parameter |
function merge<T, U>(a: T, b: U): T & U { return { ...a, ...b } } | Multiple type parameters |
function getLen<T extends { length: number }>(x: T): number { return x.length } | Generic constraint — T must have a length property |
function prop<T, K extends keyof T>(obj: T, key: K): T[K] | Constrained to keys of T — type-safe property access |
function create<T>(ctor: new () => T): T { return new ctor() } | Generic with constructor constraint |
class Container<T> { constructor(public value: T) {} } | Generic class |
function parse<T = string>(input: unknown): T | Default generic parameter |
const identity = <T,>(arg: T): T => arg | Generic arrow function (trailing comma for JSX compatibility) |
function isArray<T>(val: T | T[]): val is T[] | Generic type predicate |
Enums
| Command | Description |
|---|---|
enum Direction { Up, Down, Left, Right } | Numeric enum — auto-increments from 0 |
enum Status { Active = 1, Inactive = 2 } | Numeric enum with explicit values |
enum Color { Red = "RED", Green = "GREEN", Blue = "BLUE" } | String enum — each member has a string value |
enum Mixed { No = 0, Yes = "YES" } | Heterogeneous enum (not recommended) |
const enum Direction { Up, Down } | Const enum — inlined at compile time, no runtime object |
Direction.Upe.g. // 0 | Access enum member value |
Direction[0]e.g. // "Up" | Reverse mapping (numeric enums only) |
type Dir = keyof typeof Direction | Get enum member names as a union type |
function move(dir: Direction) {} | Use enum as a parameter type |
const Status = { Active: "active", Inactive: "inactive" } as const | Alternative: const object with as const (often preferred over enums) |
Utility Types
| Command | Description |
|---|---|
Partial<User>e.g. // { name?: string; age?: number } | Make all properties optional |
Required<User> | Make all properties required |
Readonly<User> | Make all properties readonly |
Pick<User, "name" | "email"> | Select specific properties from a type |
Omit<User, "password"> | Remove specific properties from a type |
Record<string, number>e.g. const scores: Record<string, number> = { math: 95 } | Create an object type with specific key and value types |
Record<"a" | "b", User> | Record with union key type |
Exclude<"a" | "b" | "c", "a">e.g. // "b" | "c" | Remove types from a union |
Extract<"a" | "b" | "c", "a" | "b">e.g. // "a" | "b" | Keep only matching types from a union |
NonNullable<string | null | undefined>e.g. // string | Remove null and undefined from a type |
ReturnType<typeof fn> | Get the return type of a function |
Parameters<typeof fn> | Get parameter types as a tuple |
ConstructorParameters<typeof MyClass> | Get constructor parameter types |
InstanceType<typeof MyClass> | Get the instance type of a class constructor |
Awaited<Promise<string>>e.g. // string | Unwrap a Promise type |
ThisParameterType<typeof fn> | Extract the this parameter type |
OmitThisParameter<typeof fn> | Remove the this parameter from a function type |
Uppercase<"hello">e.g. // "HELLO" | Intrinsic string manipulation type |
Lowercase<"HELLO">e.g. // "hello" | Convert string literal to lowercase |
Capitalize<"hello">e.g. // "Hello" | Capitalize first letter |
Uncapitalize<"Hello">e.g. // "hello" | Lowercase first letter |
Type Guards
| Command | Description |
|---|---|
typeof x === "string" | typeof guard — narrow to primitive types |
x instanceof Date | instanceof guard — narrow to class instances |
"name" in obj | in operator — check if property exists |
function isString(x: unknown): x is string { return typeof x === "string" } | Type predicate — custom type guard function |
function isUser(x: any): x is User { return x && typeof x.name === "string" } | Type predicate for complex types |
function assertString(x: unknown): asserts x is string { if (typeof x !== "string") throw new Error() } | Assertion function — throws if type doesn't match |
if (x !== null && x !== undefined) { /* x is narrowed */ } | Truthiness narrowing |
if (result.ok) { result.data } else { result.error } | Discriminated union narrowing |
const val = x as string | Type assertion — tell compiler to treat as specific type (use sparingly) |
const val = <string>x | Type assertion (angle bracket syntax, not usable in JSX) |
const val = x! | Non-null assertion — tell compiler value is not null/undefined |
x satisfies Typee.g. const colors = { red: "#ff0000" } satisfies Record<string, string> | satisfies operator — validate type without widening (TS 5.0+) |
Mapped Types
| Command | Description |
|---|---|
type Optional<T> = { [K in keyof T]?: T[K] } | Make all properties optional (like Partial) |
type ReadonlyAll<T> = { readonly [K in keyof T]: T[K] } | Make all properties readonly |
type Mutable<T> = { -readonly [K in keyof T]: T[K] } | Remove readonly from all properties |
type Concrete<T> = { [K in keyof T]-?: T[K] } | Remove optionality from all properties (like Required) |
type Nullable<T> = { [K in keyof T]: T[K] | null } | Make all properties nullable |
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] } | Key remapping with template literal types (TS 4.1+) |
type EventHandlers<T> = { [K in keyof T as `on${Capitalize<string & K>}`]: (val: T[K]) => void } | Create event handler types from an interface |
type FilterByType<T, U> = { [K in keyof T as T[K] extends U ? K : never]: T[K] } | Filter properties by value type |
Conditional Types
| Command | Description |
|---|---|
type IsString<T> = T extends string ? true : false | Basic conditional type |
type Flatten<T> = T extends Array<infer U> ? U : T | infer keyword — extract type from a pattern |
type UnwrapPromise<T> = T extends Promise<infer U> ? UnwrapPromise<U> : T | Recursive conditional type — deeply unwrap promises |
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never | Extract return type using infer |
type Head<T> = T extends [infer H, ...any[]] ? H : never | Extract first element of a tuple |
type Tail<T> = T extends [any, ...infer R] ? R : never | Extract all elements except first from a tuple |
type IsNever<T> = [T] extends [never] ? true : false | Check if a type is never (wrap in tuple to avoid distribution) |
type NonNullableProps<T> = { [K in keyof T]: NonNullable<T[K]> } | Remove null/undefined from all property types |
Decorators
| Command | Description |
|---|---|
@sealed
class Greeter {} | Class decorator — applied to the class constructor |
function sealed(constructor: Function) { Object.seal(constructor); Object.seal(constructor.prototype) } | Class decorator implementation |
@log
greet() { return "hello" } | Method decorator — applied to a method |
function log(target: any, key: string, descriptor: PropertyDescriptor) { /* wrap method */ } | Method decorator implementation (legacy) |
@readonly
name = "world" | Property decorator |
function validate(@required name: string) {} | Parameter decorator |
@Component({ selector: "app" })
class App {} | Decorator factory — returns a decorator function |
function Component(config: any) { return function(ctor: Function) { /* ... */ } } | Decorator factory implementation |
Module System
| Command | Description |
|---|---|
export const name = "value" | Named export |
export function helper() {} | Named export of a function |
export default class App {} | Default export |
export type { User } | Type-only export — removed at compile time |
import { name } from "./module" | Named import |
import type { User } from "./types" | Type-only import — ensures no runtime import |
import * as utils from "./utils" | Namespace import |
import defaultExport from "./module" | Default import |
export { name as renamed } from "./module" | Re-export with rename |
export * from "./module" | Re-export everything from a module |
declare module "*.css" { const classes: Record<string, string>; export default classes } | Module declaration — type CSS/image imports |
/// <reference types="vite/client" /> | Triple-slash directive — reference type definitions |
Common Patterns
| Command | Description |
|---|---|
type Brand<T, B> = T & { __brand: B }
type USD = Brand<number, "USD"> | Branded types — prevent mixing similar primitive types |
const exhaustive = (x: never): never => { throw new Error(`Unexpected: ${x}`) } | Exhaustive check — ensure all cases in a switch are handled |
type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] } | Deep partial — recursively make all properties optional |
type DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K] } | Deep readonly — recursively make all properties readonly |
function createStore<T>(initial: T) { let state = initial; return { get: () => state, set: (v: T) => { state = v } } } | Generic factory function with type inference |
type Prettify<T> = { [K in keyof T]: T[K] } & {} | Prettify — flatten intersection types for better IntelliSense display |
type StrictOmit<T, K extends keyof T> = Omit<T, K> | Strict Omit — only allow keys that actually exist on T |
const tuple = <T extends readonly unknown[]>(...args: T) => args | Tuple helper — infer tuple types from arguments |
type PathKeys<T> = T extends object ? { [K in keyof T]: K extends string ? K | `${K}.${PathKeys<T[K]>}` : never }[keyof T] : never | Recursive path type — get all nested property paths as dot notation |
interface Register {}
type Config = Register extends { config: infer C } ? C : DefaultConfig | Module augmentation pattern — let consumers extend your library's types |
📖 Free, searchable command reference. Bookmark this page for quick access.