Reputation: 1621
What I try to achive is array from declare type.
Using enum I can achive it like this:
export enum Day {
SU = 'su',
MO = 'mo',
TU = 'tu',
WE = 'we',
TH = 'th',
FR = 'fr',
SA = 'sa',
}
getDays(): String[] {
return Object.values(Day);
}
Output will be ['su', 'mo' etc. ]
I want to achive similar way from this one:
export declare type WeekDays = 'su' | 'mo' | 'tu' | 'we' | 'th' | 'fr' | 'sa';
with similar output as: ['su', 'mo' etc. ]
Any ideas?
I tried Object.entries()
and Object.getOwnPropertyNames()
. unfortunately it doesn't work.
Upvotes: 1
Views: 51
Reputation: 249646
WeekDays
is just a type, types do no have any runtime presence so we can't access any information the type holds at runtime. Enums are represented as objects at runtime, this is why we can extract information from them. See more here for a discussion on types vs values.
Baring a custom compiler transformation (which means replacing the stock compiler with a custom version that emits extra information) the only thing we can do is construct a function to retrieve the values, which requires us to pass in an object literal that contains exactly the strings in the enum. While this requires us to restate the strings, the compiler will check that we don't add any extra ones and we don't have any missing, so it might be good enough:
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);
}
// Ok values are all stated, the values are correctly stated.
getValues<WeekDays>({fr: 'fr',mo: 'mo',sa:'sa',su:'su',th:'th',tu:'tu',we:'we'})
// Error values don't match
getValues<WeekDays>({fr: 'frrr',mo: 'mo',sa:'sa',su:'su',th:'th',tu:'tu',we:'we'})
// Error values missing
getValues<WeekDays>({mo: 'mo',sa:'sa',su:'su',th:'th',tu:'tu',we:'we'})
// Error values extra values
getValues<WeekDays>({funDay: 'funDay', fr: 'fr', mo: 'mo',sa:'sa',su:'su',th:'th',tu:'tu',we:'we'})
Upvotes: 2
Reputation: 12619
All types in typescrpt are metadata only and are not available on run time. So the list of valid strings in your string literal type cannot be retrieved.
Upvotes: 1