How to use Discriminated Unions In Typescript
Discriminated Unions, also known as tagged unions or algebraic data types, allow TypeScript to narrow down the possible types within a function based on a common discriminator property.
Example: In this example, we define a discriminated union Shape with two possible shapes: Circle and Square. We create a function calculateArea that calculates the area based on the shape passed. TypeScript intelligently infers the types within the function, ensuring type safety.
// Define a discriminated union
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; sideLength: number };
// Function to calculate area based on shape
function calculateArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.sideLength ** 2;
default:
// Handle unexpected cases
throw new Error("Invalid shape");
}
}
const circleArea = calculateArea({ kind: "circle", radius: 5 });
const squareArea = calculateArea({ kind: "square", sideLength: 4 });
console.log("Area of circle:", circleArea);
console.log("Area of square:", squareArea);
Output:
Area of circle: 78.53981633974483
Area of square: 16
How to Create TypeScript Generic Function with Safe Type Matching ?
In TypeScript, generic functions offer a powerful tool for creating flexible and reusable code that can work with various data types. However, ensuring type safety is crucial to prevent runtime errors and maintain code reliability.