spinny:~/writing $ vim advanced-typescript-patterns.md
1~2TypeScript 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.3~4## 1. Generic Constraints5~6Generics are powerful, but sometimes you need to limit what can be passed in. `extends` is your friend here.7~8```typescript9interface HasId {10 id: string;11}12~13function getById<T extends HasId>(list: T[], id: string): T | undefined {14 return list.find((item) => item.id === id);15}16```17~18By ensuring `T` extends `HasId`, we guarantee that accessing `.id` inside the function is safe.19~20## 2. Conditional Types21~22Conditional types allow you to create non-uniform type mappings. The syntax is similar to the ternary operator in JavaScript.23~24```typescript25type IsString<T> = T extends string ? true : false;26~27type A = IsString<string>; // true28type B = IsString<number>; // false29```30~31A practical use case is filtering out types from a union:32~33```typescript34type Diff<T, U> = T extends U ? never : T;35type NonNullable<T> = Diff<T, null | undefined>;36```37~38## 3. Mapped Types39~40Mapped types allow you to create new types based on old ones by transforming properties.41~42```typescript43type ReadOnly<T> = {44 readonly [P in keyof T]: T[P];45};46~47interface User {48 name: string;49 age: number;50}51~52type ReadOnlyUser = ReadOnly<User>;53```54~55You can even add or remove modifiers:56~57```typescript58type Mutable<T> = {59 -readonly [P in keyof T]: T[P];60};61```62~63## 4. Template Literal Types64~65Introduced in TypeScript 4.1, these allow you to manipulate string types directly.66~67```typescript68type World = 'world';69type Greeting = `hello ${World}`; // "hello world"70~71type Color = 'red' | 'blue';72type Quantity = 'light' | 'dark';73~74type Palette = `${Quantity}-${Color}`;75// "light-red" | "light-blue" | "dark-red" | "dark-blue"76```77~78This is incredibly useful for typing strings that follow a specific pattern, like CSS classes or event names.79~80## 5. The `infer` Keyword81~82The `infer` keyword within conditional types allows you to extract types from other types.83~84```typescript85type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;86~87function check(): boolean {88 return true;89}90~91type CheckReturn = ReturnType<typeof check>; // boolean92```93~94Here, we are asking TypeScript to "infer" the return type `R` of a function and return it.95~96## Conclusion97~98Mastering 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~
NORMAL · advanced-typescript-patterns.md [readonly]99 lines · :q to close