Literal Status Type
Write a TypeScript function that uses a string literal union type for status values. Define a parameter with type 'active' | 'inactive' and return a corresponding message.
String literal types allow you to specify exact string values that a parameter can accept. TypeScript will check at compile time that only the specified strings are passed, preventing invalid status values.
Literal types are a powerful feature for creating type-safe APIs where only specific values are valid. Combined with union types, they provide compile-time validation of string values.
String literal unions are analogous to enums but with the familiar string primitives. They are useful for API response status fields, configuration modes, and finite state machines. TypeScript's compiler can narrow the type within conditional checks, providing type-safe property access.String literal unions are analogous to enums but with the familiar string primitives. They are useful for API response status fields, configuration modes, and finite state machines. TypeScript's compiler can narrow the type within conditional checks, providing type-safe property access.
The vertical bar | creates a union type. With literal types like 'active' | 'inactive', TypeScript ensures only those exact strings are accepted. Trying to pass 'pending' would cause a compile error.
Literal unions can be combined with type aliases for reuse: type Status = 'active' | 'inactive' | 'pending'. This pattern is commonly used in Redux action types and Angular route guards.
Example Input & Output
Algorithm Flow

Solution Approach
Write a TypeScript function that uses a string literal union type for status values. Define a parameter with type 'active' | 'inactive' and return a corresponding message.
String literal types allow you to specify exact string values that a parameter can accept. TypeScript will check at compile time that only the specified strings are passed, preventing invalid status values.
Literal types are a powerful feature for creating type-safe APIs where only specific values are valid. Combined with union types, they provide compile-time validation of string values.
Best Answers
function getStatusMessage(status: 'active' | 'inactive'): string {
if (status === 'active') return 'The status is active';
return 'The status is inactive';
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
