小编Ahm*_*ayo的帖子

在 Typescript 中,如何使用所述类型的文字类型属性从联合中选择类型?

我有一个减速器反应。动作可以是 8 种类型之一,但为了简单起见,我们假设只有 2 种类型

type Add = {
  type: 'add';
  id: string;
  value: string;
}

type Remove = {
  type: 'remove';
  id: string;
}

type Action = Add | Remove;
Run Code Online (Sandbox Code Playgroud)

我没有使用 switch case,而是使用了一个处理程序对象,其中每个处理程序都是一个处理特定操作的函数

const handlers = {
  add: (state, action) => state,
  remove: (state, action) => state,
  default: (state, action) => state,
}

const reducer = (state, action) => {
  const handler = handlers[action.type] || handlers.default;
  return handler(state, action);
}
Run Code Online (Sandbox Code Playgroud)

现在我想handlers适当地键入对象。所以处理函数应该接受与其在handlers对象中的键对应的类型的动作。

type Handlers = { …
Run Code Online (Sandbox Code Playgroud)

typescript

11
推荐指数
2
解决办法
5208
查看次数

标签 统计

typescript ×1