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'
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.