in operator
The JavaScript operator "key" in obj, which checks whether an object has a property and lets TypeScript narrow a union by it.
In more detail
It works when union members have no common tag: "exp" in token picks out the JSON Web Token variant. It never throws for a missing property, but the left side must be an object, so check for null first.
Related terms
- type narrowing — The compiler refining a broad type to a more specific one inside a block, after a check proves which case applies.
- instanceof — The JavaScript operator that checks whether an object was created by a given class, by walking its prototype chain.
- hasOwnProperty — A check that tells whether an object has a property itself, rather than inheriting it, even when its value is undefined.
Taught in
- Typeof Guards, Truthiness And Equality Narrowing — Production TypeScript
- The in Operator And Instanceof Narrowing — Production TypeScript
- Exhaustive Narrowing With never In Production Handlers — Production TypeScript