为什么只有一个属性的接口与具有多个属性的接口的行为不同?

thi*_*ndy 5 typescript

我刚刚开始使用 TypeScript,遇到了一些令人困惑的行为。如果我有一个interface MyInterface具有多个属性的 和 a key: keyof MyInterface,我可以使用属性的任意值创建接口的新实例key。考虑以下:

interface Values {
  one: 1;
  two: 2;
}

function getNewVals(vals: Values, key: keyof Values): Values {
  // aValue: 1 | 2, so clearly typescript knows the union of possible values
  const aValue = vals[key];
  // but this is not an error
  return { ...vals, [key]: "foo" };
  // I can do this, too
  const another: Values = { one: 1, two: 2, [key]: "foo" };
  // however, this is an error as expected, since 2 isn't assignable to the one
  // property
  vals[key] = 2;
}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果我的接口只有一个属性,则会捕获错误:

interface JustOneValue {
  one: 1;
}

function getNewJustOneVal(
  vals: JustOneValue,
  key: keyof JustOneValue
): JustOneValue {
  // this is fine now as expected
  vals[key] = 1;
  // but the following are both errors:
  // "Type of computed property's value is 'string', which is not assignable to type '1'"
  return { ...vals, [key]: "foo" };
  // "Type of computed property's value is '2', which is not assignable to type '1'"
  return { ...vals, [key]: 2 };
}
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?一方面,我希望能够说类似的话return { ...vals, [key]: (value in union of property types) };,尽管我不确定我应该能够(假设属性类型不相同),因为我不知道哪个key是。但我可以分配任何东西的事实似乎key是错误的。我是否发现了错误,或者这可以解释吗?

thi*_*ndy 0

毕竟这似乎是一个错误。我已经提交了一个问题来解决这个问题,该问题已被标记为2017 年另一个问题的重复。原因尚不完全清楚,但该错误目前似乎无法采取行动。