[英]Why can Record<string, any> equal Functions?
I was testing various typescript types till I came upon the following situation.我正在测试各种 typescript 类型,直到遇到以下情况。
Why can Record<string, any>
equal Functions?为什么
Record<string, any>
可以等于函数?
type C = { [key: string]: any } // Record<string, any>;
const C0: C = undefined // error
const C1: C = null // error
const C2: C = 2 // error
const C3: C = 'hello world' // error
const C4: C = { foo: 'bar' } // ok
const C5: C = () => undefined // ok
Yet Records<string, unknown>
can't?然而
Records<string, unknown>
不能?
type B = { [key: string]: unknown } // Record<string, unknown>;
const B0: B = undefined // error
const B1: B = null // error
const B2: B = 2 // error
const B3: B = 'hello world' // error
const B4: B = { foo: 'bar' } // ok
const B5: B = () => undefined // error
Record<string, any>
is special cased for assignability and it basically means any object type. Record<string, any>
是可分配性的特殊情况,它基本上意味着任何 object 类型。 This is explained in this GitHub issue这在此 GitHub 问题中进行了解释
Normally the source type must have an index signature if the target type does, but for: any there's really nothing implied by this (every property must match any, by definition), so we made [s: string]: any a no-op for assignability reasons.
通常,如果目标类型有,则源类型必须具有索引签名,但是对于: any 这实际上没有任何暗示(根据定义,每个属性都必须匹配 any),因此我们将 [s: string]: any 设为 no-op出于可分配性的原因。 This enabled some patterns that didn't work before:
这启用了一些以前不起作用的模式:
function doSomething(obj: { [s: string]: any}) {
// ...
}
const obj = { a: 1, b: 2 };
// WAS ERROR: 'obj' lacks index signature
doSomething(obj);
This creates some undesirable assignability in some cases, so we didn't apply this rule to: unknown so that you could pick which behavior you wanted.
这在某些情况下会产生一些不良的可分配性,因此我们没有将此规则应用于:未知,以便您可以选择您想要的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.