๐ฏ ๐ง๐๐ฝ๐ฒ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐ฃ๐ฎ๐๐๐ฒ๐ฟ๐ป๐ ๐ ๐ฆ๐๐ฒ๐ฎ๐น ๐๐ฟ๐ผ๐บ ๐ข๐ฝ๐ฒ๐ป-๐ฆ๐ผ๐๐ฟ๐ฐ๐ฒ
I read open source code to improve. I find patterns used by hundreds of people.
Here are three I use.
The satisfies operator Use this for config objects. It checks the shape. It keeps the exact value. Records lose the literal value. Satisfies keeps the literal. It helps other types.
Branded types Stop mixing up IDs. UserId and PostId are both strings. TypeScript misses this bug. Use brands. Create a Brand type. Use a helper function to cast strings. The compiler now catches the error. It costs nothing at runtime. Use it for money or user data.
The kind field Use discriminated unions for state. Stop using optional booleans for loading, success, or error. Use a kind field. Values are idle, loading, success, or error. TypeScript narrows the type in each case. You do not read data by mistake during loading. Pick one name. Use it everywhere.
Reading open source is free training. Pick a codebase you like. Read it for 30 minutes. Find a pattern. Use it on Monday.
Source: https://dev.to/sensational5510/3-typescript-patterns-i-keep-stealing-from-open-source-codebases-32be