TypeScript 将类型或接口设置为枚举的任何成员
TypeScript set a type or interface to be any member of an enum
我想知道为枚举的任何成员设置类型值的最佳方法是什么。
例子
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
我想知道为枚举的任何成员设置类型值的最佳方法是什么。
例子
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