How to use“in” operator in Typescript
The in operator in TypeScript checks for the existence of a property in an object. When used in type guards, it discerns types based on property presence. For instance, property in an object narrows the type to include the property.
Example: The function area calculates the area of a square or rectangle. It uses the in operator to distinguish between them based on property existence. If shape has sideLength, it computes the square area; otherwise, it calculates the rectangle area.
Javascript
interface Square { sideLength: number; } interface Rectangle { width: number; height: number; } function area(shape: Square | Rectangle) { if ( 'sideLength' in shape) { // Shape is narrowed to Square here return shape.sideLength ** 2; } else { // Shape is narrowed to Rectangle here return shape.width * shape.height; } } const square: Square = { sideLength: 5 }; const rectangle: Rectangle = { width: 3, height: 4 }; console.log(area(square)); console.log(area(rectangle)); |
Output:
25
12
How to implement Type narrowing in TypeScript?
Type narrowing in TypeScript refers to refining the type of a variable within a conditional block based on runtime checks. This is achieved through techniques like typeof guards, instance checks, or property existence checks, enabling more precise typing and avoiding type errors in subsequent code execution.
These are the following ways:
Table of Content
- Using typeof type guards
- Using in operator