Issue
I wanted to know what was the best way to set a type value to any member of an enum.
example
enum daysOfWeekEnum{
mon = 'Monday',
tue = 'Tuesday',
wed = 'Wednesday',
thu = 'Thursday',
fri = 'Friday',
sat = 'Saturday',
sun = 'Sunday'
}
//any day of week
type dayOfWeek = daysOfWeekEnum
//effective assign the values in this way
type day = 'Monday' | 'Tuesday' | 'Wednesday'
Solution
The enum is a type itself that can represent any value out of the set of declared values.
enum daysOfWeekEnum {
mon = 'Monday',
tue = 'Tuesday',
wed = 'Wednesday',
thu = 'Thursday',
fri = 'Friday',
sat = 'Saturday',
sun = 'Sunday'
}
let day: daysOfWeekEnum = daysOfWeekEnum.mon;
function log(value: daysOfWeekEnum) {
console.log(value);
}
log(day); // ok -- prints "Monday"
log("Monday"); // ok -- prints "Monday"
log("asdfa"); // not ok - typescript error, "asdfa" is not a daysOfWeekEnum value
Answered By - Norman Breau
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.