TypeScript: Type Annotation, Assertion, and 'satisfies' operator

Over the last few posts, I talked about how TypeScript infers types, how we can override them, and how we can validate them. Now it’s time to connect the dots. There are three main approaches - 1. Type Annotation 2. Type Assertion (as) 3. 'satisfies' operator 1. Type Annotation - You’re telling TypeScript what the type should be. This is something you should use when - 1. You want to define the shape of something upfront. 2. You’re working with function signatures, public APIs, data models, interfaces, etc. 3. You want clarity and explicitness. The downside here is that if you annotate something like an object literal too broadly (e.g., Record<string, ...>), you can lose type inference, especially for literal key names. 2. Type Assertion - You’re overriding TypeScript’s inference and saying - 'Trust me.' This is something you should use when - 1. TypeScript can’t figure out the type, but you know what it is. 2. You’re working with DOM elements or events. 3. You’re dealing with external data (like JSON or API responses). But remember that type assertion does not perform any runtime validation. If you’re wrong, TypeScript won’t save you. 3. 'satisfies' operator - You want to validate and preserve inference. 'satisfies' checks that a value conforms to a given type, without changing the inferred type. This means, Literal keys stay literal, values stay precise, and extra properties are caught as errors. So, we get the best of both worlds, meaning the object must match a required shape but inference stays as detailed as possible. This is a good option for things like configuration objects, constant maps, enum-like value objects etc. The bottom-line is that TypeScript gives you these tools for a reason. The real skill is in knowing which one to reach for depending on the situation. #TypeScript #Coding #JavaScript #WebDevelopment #Programming #SoftwareEngineering

  • table

To view or add a comment, sign in

Explore content categories