TypeScript Cheatsheet

Comprehensive TypeScript reference: types, interfaces, generics, classes, and decorators.

KeywordDescriptionSyntaxExampleCategory
stringText data typeconst name: string = "value"const name: string = "John"Types
numberNumeric data typeconst age: number = 25const score: number = 95.5Types
booleanTrue/false data typeconst active: boolean = trueconst isAdmin: boolean = falseTypes
anyDisable type checking (avoid)const x: any = valueconst x: any = "anything"Types
unknownSafe alternative to anyconst x: unknown = valueconst x: unknown = JSON.parse(data)Types
neverType that never occursfunction error(): never { throw new Error() }const x: never = neverReturns()Types
unionMultiple possible typesconst x: string | numberconst id: string | number = 123Types
literalSpecific literal valueconst x: "yes" | "no"const status: "active" | "inactive" = "active"Types
ArrayArray type declarationconst arr: string[] or Array<string>const nums: number[] = [1, 2, 3]Types
TupleFixed-length array with typesconst tuple: [string, number] = ["a", 1]const coords: [number, number] = [10, 20]Types
interfaceDefine object contractinterface Name { property: type }interface User { id: number; name: string }Interfaces
typeCreate type aliastype Name = { property: type }type User = { id: number; name: string }Interfaces
extendsExtend interface/classinterface Child extends Parent { ... }interface Admin extends User { role: string }Interfaces
Generic <T>Parameterized typesfunction func<T>(arg: T): T { ... }function identity<T>(x: T): T { return x }Generics
Generic ConstraintLimit generic typesfunction <T extends Type>function getLength<T extends { length: number }>(obj: T) { return obj.length }Generics
KeyofGet keys of a typetype Keys = keyof Typetype UserKeys = keyof UserAdvanced
TypeofGet type of a valuetype Type = typeof valuetype StringType = typeof "hello"Advanced
Conditional TypesTypes based on conditionsT extends U ? X : Ytype Check<T> = T extends string ? "yes" : "no"Advanced
Mapped TypesCreate types from existing typestype Readonly<T> = { readonly [K in keyof T]: T[K] }type ReadonlyUser = { readonly [K in keyof User]: User[K] }Advanced
classDefine a classclass Name { property: type; constructor() {} }class User { name: string; constructor(name: string) { this.name = name } }Classes
privatePrivate class memberprivate property: typeprivate password: stringClasses
protectedProtected class memberprotected property: typeprotected id: numberClasses
readonlyRead-only propertyreadonly property: typereadonly createdAt: DateClasses
@decoratorClass decorator@decorator class Name { ... }@sealed class User { ... }Decorators