你能解释为什么下面的方法不起作用吗?
enum Types {
T1 = "T1",
T2 = "T2"
}
const something = {
bool: true, // some other initial value
text: "abc", // some other initial value
type: Types // nothing yet, but has to be of type Types
}
const type1: Types = Types.T1 // OK
something.type = Types.T1 // error Type 'Types' is not assignable to type 'typeof Types'.ts(2322)
something.type = type1 // error Type 'Types' is not assignable to type 'typeof Types'.ts(2322)
答案 0 :(得分:1)
const something = {
bool: true,
text: "abc",
type: Types
}
something.type
的类型被推断为 typeof Types
,因为您为其分配了 value Types
,这是 type 的唯一值typeof Types
。如果你想先忽略赋值,你需要让类型可以为空。
const something: {bool: boolean, text: string, type: null | Types} = {
bool: true,
text: "abc",
type: null
}
我们需要一个明确的类型签名,因为没有它,something.type
的类型被推断为 null
。