【问题标题】:Assign types to argument of generic mapping function in Typescript将类型分配给 Typescript 中的通用映射函数的参数
【发布时间】:2020-04-30 04:12:04
【问题描述】:

我有一个映射数组的函数。它看起来像这样:

// opt is either `statusA` | `statusB`
options.map((opt: keyof StatusType) => {
        const activeStatus = statusCollection[opt]; //typescript doesnt scream `of any type` error
        ...

其中,StatusType 看起来像:

type Keyys = 'statusA' | 'statusB';

export type StatusType = {
  [key in Keyys]: boolean;
};

我这样做是因为我希望能够从对象中检索计算属性,以存储在上面的“activeStatus”变量中。

如果选项始终为statusType 类型,这将正常工作,但是,它是一个通用函数,我希望能够传入其他集合。我将如何定义 type 来替换 'StatusType' 使其更通用并正确利用 keyof 功能。

【问题讨论】:

    标签: javascript typescript types


    【解决方案1】:

    我在正确的轨道上。我所做的只是使用 OR | 创建一个包含不同类型定义的类型。并将其作为字符串类型的keyof 传递。

    type TypeContainer = StatusTypeA | StatusTypeB;
    
    options.map((opt: keyof sype) => {
            const activeStatus = statusCollection[opt as keyof TypeContainer];
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2023-01-16
      • 2013-11-03
      • 1970-01-01
      • 2019-01-15
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 2020-03-26
      相关资源
      最近更新 更多