[英]TypeScript set a type or interface to be any member of an enum
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.