在下面的类型定义中,为什么P1
和P2
有不同的值?
type P1 = (() => 22) extends {[k:string]:any} ? 1:2 //`P1 == 1`
type P2 = (() => 22) extends {[k:string]:unknown} ? 1:2 //`P2 == 2`
在下面的类型定义中,为什么P1
和P2
有不同的值?
type P1 = (() => 22) extends {[k:string]:any} ? 1:2 //`P1 == 1`
type P2 = (() => 22) extends {[k:string]:unknown} ? 1:2 //`P2 == 2`
请参见Breaking Change: { [k: string]: unknown }
is no longer a wildcard assignment target以获得权威答案.
index signature {[k: string]: any}
在TypeScrip中表现特殊:它是任何对象类型的有效赋值目标.通常,像() => 22
这样的类型不会被赋予implicit index signatures,因此将() => 22
赋给{[k: string]: unknown}
是错误的.只有当属性类型为any
时,您才会获得特殊的允许行为:
let anyRec: { [k: string]: any };
anyRec = () => 22; // okay
let unkRec: { [k: string]: unknown };
unkRec = () => 22; // error
这就是P1
和P2
不同的原因.