正确示例:
enum Gender {
Male,
Female
}
interface TestInterface {
age: Gender.Male
}
class Person implements TestInterface {
age: Gender.Male
}
错误示例:
enum Gender {
Male,
Female
}
interface TestInterface {
age: Gender.Male
}
class Person implements TestInterface {
age: Gender.Female
}
如上代码由于类型不匹配, 所以会报错
注意点
由于数字枚举的本质就是数值, 所以写一个数值也不会报错如下:
enum Gender {
Male,
Female
}
interface TestInterface {
age: Gender.Male
}
class Person implements TestInterface {
age: 0
}
- 如果是字符串枚举, 那么只能是枚举成员的值, 不能是其它的值
正确示例:
enum Gender {
Male = 'BNTang',
Female = 'Jonathon_Lee'
}
interface TestInterface {
age: Gender.Male
}
class Person implements TestInterface {
age: Gender.Male
}
错误示例:
enum Gender {
Male = 'BNTang',
Female = 'Jonathon_Lee'
}
interface TestInterface {
age: Gender.Male
}
class Person implements TestInterface {
age: Gender.Female
}
联合枚举类型
联合类型
let value: (number | string);
value = 1;
value = 6;
value = "123";
console.log(value);
enum Gender {
Male,
Female
}
interface TestInterface {
age: Gender
}
class Person implements TestInterface {
age: Gender.Male
}
|
请发表评论