【发布时间】:2021-08-10 03:23:51
【问题描述】:
我已将问题归结为几行代码。本质上,我正在接收一个对象并希望将其转换为接口。但是,在进行强制转换时不会强制执行枚举。这是一个简化的示例,显示未强制执行枚举。如何正确地将对象转换为接口?
enum Color {
Blue,
Green,
Brown
}
interface Person {
eye: Color
}
const myObj: any = {
eye: 'Orange'
};
const myPerson: Person = myObj;
console.log(myPerson.eye); // Prints 'Orange'
【问题讨论】:
-
呃,不要用
any? -
@Bergi 是对的。如果您只是将演员表移除到
any,那么一切都会按您的预期进行。您的代码显示Type 'string' is not assignable to type 'Color'错误:tsplay.dev/Nal96w
标签: javascript typescript enums casting enumeration