我想知道为枚举的任何成员设置类型值的最佳方式是什么。
示例
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'
枚举本身是一个类型,可以表示声明值集中的任何值。
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