考虑以下示例:
function foo<T extends string>(t: T): Record<T, string> {
let r1: Record<string, string> = { bar: "baz" }
r1.foo = "Some other property"
const r2: { [P in T]: string } = r1 // "manual" mapped type
// error (expected); Record<string, string> not assignable to {[P in T]: string}
const r3: Record<T, string> = r1 // built-in type; internally a mapped type, too
// works? Isn't the declaration the same as above?
return r1; // this shouldn't be compatible with declared return type
};
const t = foo("a")
r1
不能分配给r2
,并且会按预期触发错误。 r1
可分配给r3
,我认为这是错误的。 Record<string, string>
与Record<T, string>
不同。此外,我认为Record<T, string>
与{ [P in T]: string }
等价。因此出现以下问题:
Record<T, string>
为什么与{ [P in T]: string }
不同?r1
分配给r3
(这是一个错误)?