spinny:~/writing $ less advanced-typescript-patterns.md
12TypeScript has become the industry standard for large-scale web development. While most developers know the basics of interfaces and types, the real power lies in its advanced type system. Here are 5 patterns that will distinguish you as a senior engineer.34## 1. Generic Constraints56Generics are powerful, but sometimes you need to limit what can be passed in. `extends` is your friend here.78```typescript9interface HasId {10 id: string;11}1213function getById<T extends HasId>(list: T[], id: string): T | undefined {14 return list.find((item) => item.id === id);15}16```1718By ensuring `T` extends `HasId`, we guarantee that accessing `.id` inside the function is safe.1920## 2. Conditional Types2122Conditional types allow you to create non-uniform type mappings. The syntax is similar to the ternary operator in JavaScript.2324```typescript25type IsString<T> = T extends string ? true : false;2627type A = IsString<string>; // true28type B = IsString<number>; // false29```3031A practical use case is filtering out types from a union:3233```typescript34type Diff<T, U> = T extends U ? never : T;35type NonNullable<T> = Diff<T, null | undefined>;36```3738## 3. Mapped Types3940Mapped types allow you to create new types based on old ones by transforming properties.4142```typescript43type ReadOnly<T> = {44 readonly [P in keyof T]: T[P];45};4647interface User {48 name: string;49 age: number;50}5152type ReadOnlyUser = ReadOnly<User>;53```5455You can even add or remove modifiers:5657```typescript58type Mutable<T> = {59 -readonly [P in keyof T]: T[P];60};61```6263## 4. Template Literal Types6465Introduced in TypeScript 4.1, these allow you to manipulate string types directly.6667```typescript68type World = 'world';69type Greeting = `hello ${World}`; // "hello world"7071type Color = 'red' | 'blue';72type Quantity = 'light' | 'dark';7374type Palette = `${Quantity}-${Color}`;75// "light-red" | "light-blue" | "dark-red" | "dark-blue"76```7778This is incredibly useful for typing strings that follow a specific pattern, like CSS classes or event names.7980## 5. The `infer` Keyword8182The `infer` keyword within conditional types allows you to extract types from other types.8384```typescript85type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;8687function check(): boolean {88 return true;89}9091type CheckReturn = ReturnType<typeof check>; // boolean92```9394Here, we are asking TypeScript to "infer" the return type `R` of a function and return it.9596## Conclusion9798Mastering these patterns allows you to write libraries and utilities that are robust and provide excellent developer experience (DX). The goal of advanced TypeScript is not complexity for complexity's sake, but safety and expressiveness.99
:5 Advanced TypeScript Patterns for Senior Engineerslines 1-99 (END) — press q to close