Hone logo
Hone
Problems

String Literal Types: Defining Specific String Values

String literal types in TypeScript allow you to define types that represent a specific set of string values. This is incredibly useful for creating more type-safe code, preventing errors by ensuring that variables and function parameters only accept the expected string values. This challenge will test your understanding of how to create and utilize string literal types effectively.

Problem Description

You are tasked with creating a set of utility functions that leverage string literal types to enforce specific string values. You will define a type OrderStatus which represents the possible states of an order (e.g., "pending", "shipped", "delivered", "cancelled"). Then, you'll create two functions: validateOrderStatus and processOrder.

validateOrderStatus should take a string as input and return a boolean indicating whether the input string is a valid OrderStatus.

processOrder should take an OrderStatus as input and return a string describing the order processing action. The actions should be different for each order status.

Examples

Example 1:

Input: validateOrderStatus("shipped")
Output: true
Explanation: "shipped" is a valid OrderStatus.

Example 2:

Input: validateOrderStatus("processing")
Output: false
Explanation: "processing" is not a valid OrderStatus.

Example 3:

Input: processOrder("pending")
Output: "Order is pending. Awaiting payment."
Explanation: The function returns the appropriate message for the "pending" status.

Example 4:

Input: processOrder("delivered")
Output: "Order has been successfully delivered."
Explanation: The function returns the appropriate message for the "delivered" status.

Constraints

  • The OrderStatus type must be defined using string literal types.
  • validateOrderStatus must return true only if the input string exactly matches one of the values defined in OrderStatus.
  • processOrder must return a different string for each valid OrderStatus.
  • The solution must be written in TypeScript.

Notes

  • Consider using a type alias to define OrderStatus.
  • The processOrder function can use a switch statement or a similar approach to handle different order statuses.
  • Focus on type safety and ensuring that the functions only accept valid OrderStatus values. TypeScript's type checking should prevent invalid inputs. Don't rely on runtime checks for validity.
Loading editor...
typescript