Hone logo
Hone
Problems

Implementing a Discriminated Union Parameter Type in TypeScript

This challenge focuses on creating a robust and type-safe function that accepts a discriminated union as a parameter. Discriminated unions are a powerful TypeScript feature allowing you to represent a type that can be one of several distinct types, each with a common discriminant property. This is useful for handling different kinds of events, API responses, or user inputs in a structured and type-safe manner.

Problem Description

You need to implement a function called processData that accepts a parameter of type Data. The Data type is a discriminated union consisting of three possible types: Success, Error, and Loading. Each type has a distinct discriminant property: status for Success and Error, and type for Loading. The function should then perform different actions based on the status or type property of the input Data object.

Specifically:

  • If the input is a Success object, log a success message including the data property.
  • If the input is an Error object, log an error message including the message property.
  • If the input is a Loading object, log a loading message including the message property.

The function must be type-safe, meaning the TypeScript compiler should be able to verify that the function is called with valid Data objects and that the correct properties are accessed based on the type of the object.

Examples

Example 1:

Input: { status: 'success', data: { id: 123, name: 'Example' } }
Output: "Success: { id: 123, name: 'Example' }"
Explanation: The input is a Success object. The function logs a success message including the data.

Example 2:

Input: { status: 'error', message: 'Failed to fetch data' }
Output: "Error: Failed to fetch data"
Explanation: The input is an Error object. The function logs an error message including the message.

Example 3:

Input: { type: 'loading', message: 'Fetching data...' }
Output: "Loading: Fetching data..."
Explanation: The input is a Loading object. The function logs a loading message including the message.

Constraints

  • The Data type must be a discriminated union as described above.
  • The processData function must be type-safe.
  • The function should handle all three possible types of the Data union.
  • The logging messages should be formatted as specified in the examples.

Notes

Consider using TypeScript's conditional types and type guards to achieve type safety and handle each case appropriately. Think about how to leverage the discriminant properties to narrow down the type of the input object within the function. The goal is to write code that is both functional and demonstrates a good understanding of TypeScript's advanced type system.

Loading editor...
typescript