代码之家  ›  专栏  ›  技术社区  ›  Get Off My Lawn

如何使用字符串类型引用对象键的值?

  •  1
  • Get Off My Lawn  · 技术社区  · 3 年前

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

    type Add = {
      type: 'add';
      id: string;
      value: string;
    }
    
    type Remove = {
      type: 'remove';
      id: string;
    }
    
    type Action = Add | Remove;
    

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

    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);
    }
    

    现在我想键入 handlers 对象。因此,处理程序函数应该接受与它在 处理程序 对象

    type Handlers = {
      [key in Action["type"]]: (state: State, action: Action) => State
    //                                                ↑this here should be the action which has type
    //                                                matching to it's key. So when the key is
    //                                                'add', it should be of type Add, and so on.
    }
    

    我所能想到的就是明确地声明键和匹配的操作类型。有没有办法根据键的值从并集中“挑选”类型?

    0 回复  |  直到 5 年前
    推荐文章