记录类型的行为与映射类型不同

时间:2020-03-25 16:21:28

标签: typescript

考虑以下示例:

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 }等价。因此出现以下问题:

  1. 在可分配性方面,Record<T, string>为什么与{ [P in T]: string }不同?
  2. 为什么我可以将r1分配给r3(这是一个错误)?

0 个答案:

没有答案
相关问题