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
OrderStatustype must be defined using string literal types. validateOrderStatusmust returntrueonly if the input string exactly matches one of the values defined inOrderStatus.processOrdermust return a different string for each validOrderStatus.- The solution must be written in TypeScript.
Notes
- Consider using a type alias to define
OrderStatus. - The
processOrderfunction can use aswitchstatement or a similar approach to handle different order statuses. - Focus on type safety and ensuring that the functions only accept valid
OrderStatusvalues. TypeScript's type checking should prevent invalid inputs. Don't rely on runtime checks for validity.