๐ง๐๐ฝ๐ฒ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐ฆ๐ฎ๐๐ถ๐๐ณ๐ถ๐ฒ๐ ๐ข๐ฝ๐ฒ๐ฟ๐ฎ๐๐ผ๐ฟ: ๐ฆ๐๐ผ๐ฝ ๐๐ผ๐๐ถ๐ป๐ด ๐ฌ๐ผ๐๐ฟ ๐ง๐๐ฝ๐ฒ๐
Do you use type annotations for objects? You might be losing valuable data.
When you define an object with a type annotation, TypeScript widens your types.
If you define a route: const routes: Record<string, RouteConfig> = { "/dashboard": { path: "/dashboard", auth: true } };
TypeScript sees "auth" as a boolean. It forgets that it is specifically "true". You lose the narrow literal types you need for strict logic.
You have two bad options before TypeScript 4.9:
No annotation: You get narrow types, but you lose validation. If you make a typo in a property name, TypeScript stays silent. You only find the error at runtime.
Type assertion (using "as"): You tell TypeScript to trust you. This suppresses errors. If you miss a required field or make a typo, TypeScript will not warn you. You lose safety and narrow types at the same time.
The Solution: The satisfies operator.
The satisfies operator validates your object without changing its inferred type. It gives you the best of both worlds: validation and narrow types.
Why it works:
- It checks that your object matches a specific shape.
- It catches typos and missing fields.
- It preserves exact values like specific strings or booleans.
Real world examples:
โข Theme objects: Keep your specific color names instead of widening everything to a general string. This keeps your autocomplete working perfectly.
โข Status maps: Ensure every status color is valid. If you use "gray" instead of "red" or "green," TypeScript catches it immediately.
โข Event handlers: Ensure every function in a map follows the same signature while keeping the unique argument types for each specific handler.
When to use each method:
- Use Type Annotations: When you need the value to strictly become that type for other functions or APIs.
- Use Type Assertion (as): Only when you know more than TypeScript, such as parsing JSON.
- Use satisfies: When you want to validate a structure but keep your specific, narrow types.
Stop choosing between safety and precision. Use satisfies to get both.