How to Convert TypeScript Enums to Strings
When working with TypeScript enum values, you'll often need to display them as readable strings in UI elements, logs, or messages. Converting enums to strings is a common task that can be approached in several ways. This article covers practical methods for transforming enum values into their string representations, creating custom string mappings, and extracting enum keys for display purposes.
Converting a TypeScript Enum to a String
To convert a TypeScript enum to a string, you can use this straightforward approach:
enum Status {
Active,
Inactive,
Pending
}
const status = Status.Active;
const statusString = Status[status]; // "Active"
console.log(statusString); // Output: "Active"
This approach works because TypeScript creates a reverse mapping in numeric enums, allowing you to look up the name of an enum value. This method is perfect for quick conversions when you need the exact name of the enum member.
This technique is useful for displaying enum values in your UI components or debug messages in your Convex apps.
Mapping TypeScript Enums to String Representations
To map each enum to its string representation, use an object that stores enum values as keys and their string representations as values:
enum UserRole {
Admin,
User,
Guest
}
const userRoleMap: { [key in UserRole]: string } = {
[UserRole.Admin]: 'Administrator',
[UserRole.User]: 'Registered User',
[UserRole.Guest]: 'Site Guest'
};
const userRole = UserRole.Admin;
const userRoleString = userRoleMap[userRole]; // "Administrator"
console.log(userRoleString); // Output: "Administrator"
This technique uses the Map
type to create a lookup object that pairs each enum value with its custom string representation. It's perfect for internationalization or when you need to display text that differs from the enum's technical name.
For real-world applications, you could integrate this with Convex's type system to ensure your backend and frontend use consistent enum representations.
Extracting String Names from a TypeScript Enum
To extract a string name from a TypeScript enum, use the following method:
enum Status {
Active,
Inactive,
Pending
}
const status = Status.Active;
const statusString = Status[status]; // "Active"
console.log(statusString); // Output: "Active"
This method works well with the typeof
operator when you need to maintain type safety while working with enum names. It's particularly valuable in end-to-end type safety scenarios when sending enum data between client and server.
Iterating Over a TypeScript Enum and Getting String Values
To iterate over a TypeScript enum and get string values, use Object.keys()
or a for...in
loop:
enum Status {
Active,
Inactive,
Pending
}
// Using Object.keys()
Object.keys(Status).forEach((key) => {
console.log(key); // Output: "Active", "Inactive", "Pending"
});
// Using for...in loop
for (const key in Status) {
if (isNaN(Number(key))) {
console.log(key); // Output: "Active", "Inactive", "Pending"
}
}
The isNaN(Number(key))
check is crucial because TypeScript creates a bidirectional mapping for numeric enums, meaning both names and values are accessible as keys. This filtering ensures you only get the string names.
This pattern works well with Convex's data models when you need to present all possible enum values in a dropdown or selection component. You could also combine this with the Array
methods to transform enum values into format-specific representations.
Using TypeScript Enums as String Keys in Object Lookups
When you need to use enum string names as keys in objects, you can combine the bracket notation with object literal syntax:
enum Status {
Active,
Inactive,
Pending
}
const statusMap: { [key: string]: string } = {
[Status[Status.Active]]: 'Active status',
[Status[Status.Inactive]]: 'Inactive status',
[Status[Status.Pending]]: 'Pending status'
};
const status = Status.Active;
const statusString = Status[status]; // "Active"
const statusDescription = statusMap[statusString]; // "Active status"
console.log(statusDescription); // Output: "Active status"
This pattern creates a flexible lookup mechanism where your enum string names serve as keys to retrieve associated data. It works well with the switch
statement alternative when you need more complex logic based on enum values.
Outputting TypeScript Enum Values as Strings for Debugging
To output TypeScript enum values as strings for debugging, use this approach:
enum Status {
Active,
Inactive,
Pending
}
const status = Status.Active;
const statusString = Status[status]; // "Active"
console.log(`Status: ${statusString}`); // Output: "Status: Active"
This straightforward approach makes your log outputs much more useful than displaying numeric enum values. You can use template literals to embed the string representation in a message.
For Convex applications, this technique integrates well with the logging system when tracking application state or debugging issues with your keyof
operator usage.
Creating a Function to Return String Names from Enum Values
To create a function that returns string names from enum values, use this method:\
enum Status {
Active,
Inactive,
Pending
}
function getStatusString(status: Status): string {
return Status[status];
}
const status = Status.Active;
const statusString = getStatusString(status); // "Active"
console.log(statusString); // Output: "Active"
This approach centralizes the conversion logic, making your code more maintainable. It's useful when you need to perform the same conversion in multiple places throughout your application.
Final Thoughts
Converting TypeScript enums to strings simplifies data presentation and debugging. By using bracket notation, creating custom mappings, extracting names, and iterating over enum values, you can work with enums more effectively in your applications. These techniques help bridge the gap between TypeScript's type-safe enums and user-facing string representations.
When building full-stack TypeScript apps, these methods ensure consistent data handling across your frontend and backend, especially in TypeScript-first environments where type safety is a priority.