网站搜索

Typescript 语法循环遍历类型 -- let type Types=typeof myObject[number]


很难找到信息,因为我不知道这叫什么,只能从上下文判断它在做什么。它在下面的这个例子中被使用。

https://github.com/piotrwitek/react-redux-typescript-guide#typing-reducer

// inferring union type of actions
import { $call } from 'utility-types';
import * as actions from './actions';
const returnsOfActions = Object.values(actions).map($call);
export type TodosAction = typeof returnsOfActions[number];

特别是最后一行。number 没有定义,但它似乎在循环遍历数组 returnOfActions。基本上,这是否等同于执行

export type TodosAction = ActionType1 | ActionType2 | ...

你会把这种类型的语法称为什么(这样我可以读更多)

答案#1

我也对这种语法感到好奇。原来这就是你所说的查找类型。最好在 Typescript 2.1 的公告博客中解释,这里是链接。

在你的情况下,如果我们明确写出类型,事情会更容易理解,

  • 写出类型

    interface Actions {
      [index: number] = ActionType1 | ActionType2
    }
    
  • 在这里明确声明类型

    const returnsOfActions: Actions = Object.values(actions).map($call);
    
  • 这句话的意思是获取由数字索引的类型。在我们的例子中是 ActionType1 | ActionType2

    export type TodosAction = typeof returnsOfActions[number];