这是TypeScript的一个已知问题,记录在
microsoft/TypeScript#38663
如果你有
computed property name
其类型为
union
,那么TypeScript将把该类型一直扩展到
string
(参见
microsoft/TypeScript#13948
),然后或多或少完全忽略了该属性。也就是说,这比分配一个
number
到
a
,它可以分配
任何东西
到
一
,包括
false
(参见
this playground link
).
它目前还没有被归类为bug,可能是因为这种属性写入的不健全渗透到了语言中:
// widen the type of value, this is considered "safe"
const myVal: { [k: string]: string | number } = value;
// but oops:
myVal.b = "oopsieDoodle";
修复这种不健全会使事情更安全,但可以说使用起来更烦人,正如许多关于
microsoft/TypeScript#30769
TypeScript是不健全的,主要是在TS团队认为治愈比疾病更糟糕的地方。请参阅
TypeScript Language Design Non-Goal #3
TS团队的评论
microsoft/TypeScript#9825
.