【问题标题】:Problem with Typescript interface and dynamic properties using genericsTypescript 接口和使用泛型的动态属性的问题
【发布时间】:2021-11-20 09:15:45
【问题描述】:

这个函数

function abc<K extends keyof any>(
  param: K,
) {
  const z: { [p in K]: string } = {
    [param]: 'abc',
  };
}

给出以下错误:

TS2322: Type '{ [x: string]: string; }' is not assignable to type '{ [p in K]: string; }'.

在打字稿中不可能有这样的事情吗? 我正在使用 Typescript 4.3.5

谢谢

何塞

【问题讨论】:

标签: typescript typescript-generics dynamic-properties


【解决方案1】:

您收到此错误,因为 TS 不确定 K 泛型参数。它是编译器的黑匣子。

看这个例子:

function abc<K extends PropertyKey>(
    param: K,
) {
    const z: { [p in K]: string } = {
        [param]: 'abc',
    };

    return z
}

const result2 = abc<42 | 'prop' | symbol>('prop')

keyof any 与内置的PropertyKey 相同。此外,PropertyKey 是联合类型,因此 K 也可能是联合类型。

考虑上面的例子。 K 是一个 42 | 'prop' | symbol,它是完全有效的类型并且符合要求。

因为K是联合体,理论上z应该是{ [p in 42 | 'prop' | symbol]: string }吧?所以我们应该得到一个具有三个属性的对象?但是你只提供了一个。

同样,因为K 是 TS 编译器的黑匣子,所以做出任何假设都是不安全的。

Related answer

【讨论】:

  • 我明白你的意思,谢谢。但我认为param: K 可以将K 限制为只有一种可能性。问题可能在于该约束不在静态类型范围内。
猜你喜欢
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2011-06-14
  • 2020-04-12
  • 2011-04-28
  • 1970-01-01
  • 2015-04-01
  • 2012-01-27
相关资源
最近更新 更多