【问题标题】:How to make an object key generic in a typescript interface?如何在打字稿界面中使对象键通用?
【发布时间】:2022-01-05 08:19:28
【问题描述】:

我正在尝试将接口声明中的键设为通用,这样如果我向接口传递一个字符串,则键将是一个字符串。

K 出错:An index signature parameter type must be either 'string' or 'number'

interface SomeObj<K , V> {
  bar: {
    [P in K]: V
  }
};


const foo: SomeObj<string, number> = { 
  bar: {hello: 1234}
}

【问题讨论】:

  • 你想要一个映射类型而不是索引签名......它看起来像 {[P in K]: V} 而不是 {[k: K]: V}。这相当于Record&lt;K, V&gt;。有关更多信息,请参阅链接问题的 answer
  • 这也行不通,因为P in K 会将 K 视为字符串值的联合。我正在寻找k 的类型而不是值。像 [k: string]: V] 这样的东西会起作用,但如果我替换 string with K`。它不会快乐。
  • 好吧,我重新打开了这个问题,但我不明白 Record&lt;K, V&gt; 怎么不适合你。你说“行不通”……你试过了吗?
  • 确保将错误更新为“Type 'K' is not assignable to type 'string | number | symbol'”而不是“An index signature parameter type must be either 'string' or 'number'”。

标签: typescript typescript-typings typescript-generics


【解决方案1】:

我将在这里回答我自己的问题。

每当我们构建“对象键类型”时,我们都会受到 typescript 定义的类型的限制,它们是 stringnumbersymbol,这些也是唯一被接受为 javascript 对象键的类型。

编译器不喜欢只有没有extend 的泛型类型K,因为它实际上可以是任何东西,例如null,这不是有效的键值。

因此,如果我们想将键的类型限制为可接受的类型,我们将在对象声明中传递。在这种情况下,我们必须首先告诉泛型类型K 在这种情况下string | number 可以是哪些类型。

interface SomeObj<K extends string | number , V> {
  something: {
    [key in K]: V;
  }
};

const foo: SomeObj<string, number> = { 
  something: {hello: 1234}
}
const bar: SomeObj<number, number> = { 
  something: {123: 1234}
}

【讨论】:

  • 即使K extends string | number(或者你可以写K extends PropertyKey来包含symbol),{[k: K]: V}也会编译失败。这个答案跳转到使用{[P in K]: V} 形式的映射类型,而没有提及它。您可能应该将问题更改为使用[P in K] 而不是[k: K],或者您可能应该更改答案以了解索引签名(其键不能是通用的)和映射类型(其键可以)之间的区别。
  • 另请注意,约定不是[key in K],因为您调用的key 是一个类型参数,因此应该大写且短。所以[P in K] 更好。在像[key: string] 这样的索引签名中,key 是一个虚拟键name,因此应该采用JavaScript 标识符的形式,比如小写字母。通过编写key in K,您可以使它看起来像key 是一个属性键标识符而不是类型参数名称。
  • 你说得对,谢谢。现在将更新问题。
猜你喜欢
  • 2016-09-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2021-12-17
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
相关资源
最近更新 更多