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.

JavaScript
// 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.

Similar Reads

These are the following approaches:

Table of Content Using Type constraintsUsing Type inferenceUsing Type guards...

Using Type constraints

You can specify constraints on the type parameter to ensure that only certain types are accepted....

Using Type inference

TypeScript’s type inference mechanism can automatically infer the types based on the provided arguments, reducing the need for explicit type annotations....

Using Type guards

Type guards are conditional statements that check the type of a value at runtime, ensuring that only values of the expected type are used in the function....

Using Discriminated Unions

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....

Conclusion

Enhancing type safety in TypeScript generic functions is paramount for building reliable and maintainable codebases. By leveraging type constraints, type inference, and type guards, developers can ensure that their generic functions safely handle a variety of data types, preventing runtime errors and improving code readability....