Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Advanced TypeScript expert covering type-level programming, branded types, monorepos, and migration strategies.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/typescript-cheatsheet.md
1# TypeScript Cheatsheet23## Type Basics45```typescript6// Primitives7const name: string = 'John'8const age: number = 309const isActive: boolean = true10const nothing: null = null11const notDefined: undefined = undefined1213// Arrays14const numbers: number[] = [1, 2, 3]15const strings: Array<string> = ['a', 'b', 'c']1617// Tuple18const tuple: [string, number] = ['hello', 42]1920// Object21const user: { name: string; age: number } = { name: 'John', age: 30 }2223// Union24const value: string | number = 'hello'2526// Literal27const direction: 'up' | 'down' | 'left' | 'right' = 'up'2829// Any vs Unknown30const anyValue: any = 'anything' // ❌ Avoid31const unknownValue: unknown = 'safe' // ✅ Prefer, requires narrowing32```3334## Type Aliases & Interfaces3536```typescript37// Type Alias38type Point = {39x: number40y: number41}4243// Interface (preferred for objects)44interface User {45id: string46name: string47email?: string // Optional48readonly createdAt: Date // Readonly49}5051// Extending52interface Admin extends User {53permissions: string[]54}5556// Intersection57type AdminUser = User & { permissions: string[] }58```5960## Generics6162```typescript63// Generic function64function identity<T>(value: T): T {65return value66}6768// Generic with constraint69function getLength<T extends { length: number }>(item: T): number {70return item.length71}7273// Generic interface74interface ApiResponse<T> {75data: T76status: number77message: string78}7980// Generic with default81type Container<T = string> = {82value: T83}8485// Multiple generics86function merge<T, U>(obj1: T, obj2: U): T & U {87return { ...obj1, ...obj2 }88}89```9091## Utility Types9293```typescript94interface User {95id: string96name: string97email: string98age: number99}100101// Partial - all optional102type PartialUser = Partial<User>103104// Required - all required105type RequiredUser = Required<User>106107// Readonly - all readonly108type ReadonlyUser = Readonly<User>109110// Pick - select properties111type UserName = Pick<User, 'id' | 'name'>112113// Omit - exclude properties114type UserWithoutEmail = Omit<User, 'email'>115116// Record - key-value map117type UserMap = Record<string, User>118119// Extract - extract from union120type StringOrNumber = string | number | boolean121type OnlyStrings = Extract<StringOrNumber, string>122123// Exclude - exclude from union124type NotString = Exclude<StringOrNumber, string>125126// NonNullable - remove null/undefined127type MaybeString = string | null | undefined128type DefinitelyString = NonNullable<MaybeString>129130// ReturnType - get function return type131function getUser() { return { name: 'John' } }132type UserReturn = ReturnType<typeof getUser>133134// Parameters - get function parameters135type GetUserParams = Parameters<typeof getUser>136137// Awaited - unwrap Promise138type ResolvedUser = Awaited<Promise<User>>139```140141## Conditional Types142143```typescript144// Basic conditional145type IsString<T> = T extends string ? true : false146147// Infer keyword148type UnwrapPromise<T> = T extends Promise<infer U> ? U : T149150// Distributive conditional151type ToArray<T> = T extends any ? T[] : never152type Result = ToArray<string | number> // string[] | number[]153154// NonDistributive155type ToArrayNonDist<T> = [T] extends [any] ? T[] : never156```157158## Template Literal Types159160```typescript161type Color = 'red' | 'green' | 'blue'162type Size = 'small' | 'medium' | 'large'163164// Combine165type ColorSize = `${Color}-${Size}`166// 'red-small' | 'red-medium' | 'red-large' | ...167168// Event handlers169type EventName = 'click' | 'focus' | 'blur'170type EventHandler = `on${Capitalize<EventName>}`171// 'onClick' | 'onFocus' | 'onBlur'172```173174## Mapped Types175176```typescript177// Basic mapped type178type Optional<T> = {179[K in keyof T]?: T[K]180}181182// With key remapping183type Getters<T> = {184[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]185}186187// Filter keys188type OnlyStrings<T> = {189[K in keyof T as T[K] extends string ? K : never]: T[K]190}191```192193## Type Guards194195```typescript196// typeof guard197function process(value: string | number) {198if (typeof value === 'string') {199return value.toUpperCase() // string200}201return value.toFixed(2) // number202}203204// instanceof guard205class Dog { bark() {} }206class Cat { meow() {} }207208function makeSound(animal: Dog | Cat) {209if (animal instanceof Dog) {210animal.bark()211} else {212animal.meow()213}214}215216// in guard217interface Bird { fly(): void }218interface Fish { swim(): void }219220function move(animal: Bird | Fish) {221if ('fly' in animal) {222animal.fly()223} else {224animal.swim()225}226}227228// Custom type guard229function isString(value: unknown): value is string {230return typeof value === 'string'231}232233// Assertion function234function assertIsString(value: unknown): asserts value is string {235if (typeof value !== 'string') {236throw new Error('Not a string')237}238}239```240241## Discriminated Unions242243```typescript244// With type discriminant245type Success<T> = { type: 'success'; data: T }246type Error = { type: 'error'; message: string }247type Loading = { type: 'loading' }248249type State<T> = Success<T> | Error | Loading250251function handle<T>(state: State<T>) {252switch (state.type) {253case 'success':254return state.data // T255case 'error':256return state.message // string257case 'loading':258return null259}260}261262// Exhaustive check263function assertNever(value: never): never {264throw new Error(`Unexpected value: ${value}`)265}266```267268## Branded Types269270```typescript271// Create branded type272type Brand<K, T> = K & { __brand: T }273274type UserId = Brand<string, 'UserId'>275type OrderId = Brand<string, 'OrderId'>276277// Constructor functions278function createUserId(id: string): UserId {279return id as UserId280}281282function createOrderId(id: string): OrderId {283return id as OrderId284}285286// Usage - prevents mixing287function getOrder(orderId: OrderId, userId: UserId) {}288289const userId = createUserId('user-123')290const orderId = createOrderId('order-456')291292getOrder(orderId, userId) // ✅ OK293// getOrder(userId, orderId) // ❌ Error - types don't match294```295296## Module Declarations297298```typescript299// Declare module for untyped package300declare module 'untyped-package' {301export function doSomething(): void302export const value: string303}304305// Augment existing module306declare module 'express' {307interface Request {308user?: { id: string }309}310}311312// Declare global313declare global {314interface Window {315myGlobal: string316}317}318```319320## TSConfig Essentials321322```json323{324"compilerOptions": {325// Strictness326"strict": true,327"noUncheckedIndexedAccess": true,328"noImplicitOverride": true,329330// Modules331"module": "ESNext",332"moduleResolution": "bundler",333"esModuleInterop": true,334335// Output336"target": "ES2022",337"lib": ["ES2022", "DOM"],338339// Performance340"skipLibCheck": true,341"incremental": true,342343// Paths344"baseUrl": ".",345"paths": {346"@/*": ["./src/*"]347}348}349}350```351352## Best Practices353354```typescript355// ✅ Prefer interface for objects356interface User {357name: string358}359360// ✅ Use const assertions361const routes = ['home', 'about'] as const362363// ✅ Use satisfies for validation364const config = {365api: 'https://api.example.com'366} satisfies Record<string, string>367368// ✅ Use unknown over any369function parse(input: unknown) {370if (typeof input === 'string') {371return JSON.parse(input)372}373}374375// ✅ Explicit return types for public APIs376export function getUser(id: string): User | null {377// ...378}379380// ❌ Avoid381const data: any = fetchData()382data.anything.goes.wrong // No type safety383```384