Can I convert this into an enum in type script / react native export class Tag {…
- User
Can I convert this into an enum in type script / react native
export class Tag { readonly name: string; readonly description: string; readonly icon: string;
private constructor(name: string, description: string, icon: string) { this.name = name; this.description = description; this.icon = icon; } // Define all tags like enums here static OffCampus = new Tag("Off-Campus", "This item requires you to leave campus or use transportation", "car"); static NeedEntry = new Tag("Entry Needed", "Food is behind locked doors or in a private event", "sliding-door-lock"); static NeedPhone = new Tag("Need Phone", "Bring your phone (fill out form, show voucher, etc.)", "phone");}
- Assistant
Yes, you can convert the
Tagclass into an enum in TypeScript with additional properties likedescriptionandicon. However, standard TypeScript enums cannot hold multiple properties directly—they can only map keys to unique values. To accommodate additional properties, you would typically use a combination of an enum and a dictionary (object) to hold the additional metadata.Here's a way to refactor your class into an enum-like structure in TypeScript:
// Enum to define your tag names export enum TagName { OffCampus = "OffCampus", NeedEntry = "NeedEntry", NeedPhone = "NeedPhone", } export const TagDetails = { [TagName.OffCampus]: { name: TagName.OffCampus, description: "This item requires you to leave campus or use transportation", icon: "car", }, [TagName.NeedEntry]: { name: TagName.NeedEntry, description: "Food is behind locked doors or in a private event", icon: "sliding-door-lock", }, [TagName.NeedPhone]: { name: TagName.NeedPhone, description: "Bring your phone (fill out form, show voucher, etc.)", icon: "phone", }, }; // Usage Example: const selectedTag = TagName.OffCampus; console.log(TagDetails[selectedTag].description); // Output: "This item requires you to leave campus or use transportation"Here's a breakdown of what is happening:
TagNameenum is created to define the unique tag names.TagDetailsis an object that holds additional properties (descriptionandicon) for each tag name.- When you want to use a tag's details, you can look them up in the
TagDetailsobject using the tag name from theTagNameenum.
This approach ensures that you get the benefits of
enum(like type safety and intellisense) while still maintaining the structure and additional properties of your tags.