WeekDays
is considered a type in programming, and unlike objects at runtime, types do not have any presence during execution. This means that we cannot access any information stored within a type at runtime. Enums, on the other hand, are represented as objects during runtime, allowing us to extract information from them. To learn more about the distinction between types and values, you can visit this link.
Without implementing a custom compiler transformation (which involves replacing the default compiler with a tailored version that provides extra details), our only option is to create a function for retrieving values. This function requires us to input an object literal that includes the exact strings defined in the enum. Although this may involve restating the strings, the compiler will verify that no additional strings are added and none are missing, ensuring accuracy:
export declare type WeekDays = 'su' | 'mo' | 'tu' | 'we' | 'th' | 'fr' | 'sa';
function getValues<T extends string>(values: { [P in T]: P }) : T[]{
return Object.values(values);
}
// All values correctly stated
getValues<WeekDays>({fr: 'fr', mo: 'mo', sa:'sa', su:'su', th:'th', tu:'tu', we:'we'})
// Incorrect value provided
getValues<WeekDays>({fr: 'frrr', mo: 'mo', sa:'sa', su:'su', th:'th', tu:'tu', we:'we'})
// Missing value
getValues<WeekDays>({mo: 'mo', sa:'sa', su:'su', th:'th', tu:'tu', we:'we'})
// Extra value
getValues<WeekDays>({funDay: 'funDay', fr: 'fr', mo: 'mo', sa:'sa', su:'su', th:'th', tu:'tu', we:'we'})