有没有更好的方法来告诉打字稿 "data" 是哪种类型?

Is there a better way to tell typescript which type "data" is?

我正在遵循 React action/reducer 模式 put forth by Kent Dodds 并且我正在尝试为其添加一些类型安全性。

export type Action = 
    { type: "DO_SOMETHING", data: { num: Number } } |
    { type: "DO_SOMETHING_ELSE", data: { nums: Number[] } };

type Actions = {
    [key in Action["type"]]: (state: State, data: Action["data"]) => State;
};

const actions: Actions = {
   DO_SOMETHING: (state, data) => {
       return { nums: [data.num] }; // Type error
   },
   DO_SOMETHING_ELSE: (state, data) => {
       return { nums: data.nums }; // Type error
   }
};

这段代码很好,因为它确保 actions 对象包含 Action 联合类型中列出的所有操作类型,并在尝试分派操作时提供类型安全。尝试访问 data.

的成员时出现问题
Property 'num' does not exist on type '{ num: Number; } | { nums: Number[]; }'.
  Property 'num' does not exist on type '{ nums: Number[]; }'.

但是,如果我这样做:

export type Action = 
    { type: "DO_SOMETHING", data: { num: Number } } |
    { type: "DO_SOMETHING_ELSE", data: { nums: Number[] } };

type Actions = {
    [key in Action["type"]]: (state: State, action: Action) => State;
};

const actions: Actions = {
   DO_SOMETHING: (state, action) => {
       if (action.type !== "DO_SOMETHING") return state;
       return { nums: [action.data.num] }; // No more type error
   },
   DO_SOMETHING_ELSE: (state, action) => {
       if (action.type !== "DO_SOMETHING_ELSE") return state;
       return { nums: action.data.nums }; // No more type error
   }
};

现在 TypeScript 知道 action.data 是与显式 action.type 匹配的联合类型。有没有更简洁的方法来做到这一点,而不必将所有操作内联到一个大的 switch 语句中?

PS - 这是 the full playground snippet 我一直用来测试这一切的。

type ActionDataMap = {
    DO_SOMETHING: { num: Number };
    DO_SOMETHING_ELSE: { nums: Number[] } 
};

type ActionType = keyof ActionDataMap
type ActionsMap = {
  [K in ActionType]: { type: K; data: ActionDataMap[K] }
}

// this will generate the union:
type Action = ActionsMap[ActionType]

// you can index into ActionsMap with K to find the specific Action
type Actions = {
    [K in ActionType]: (state: State, action: ActionsMap[K]) => State;
};

你们非常亲密。

(state: State, data: Action["data"]) => State; 中的这一行 Action['data'] 不正确。

Action['data'] 应该绑定 key 属性.

看这个例子:

type State = {
    nums: number[]
}
export type Action =
    | { type: "DO_SOMETHING", data: { num: number } }
    | { type: "DO_SOMETHING_ELSE", data: Pick<State, 'nums'> };

type Actions = {
    [Type in Action["type"]]: (state: State, data: Extract<Action, { type: Type }>['data']) => State;
};

const actions: Actions = {
    DO_SOMETHING: (state, data) => ({ nums: [data.num] }),
    DO_SOMETHING_ELSE: (state, data) => ({ nums: data.nums })
};

Playground

我使用 Type 而不是 key 因为我们正在迭代 types 属性.

Extract - 需要两个参数。首先 - 一个联合,第二个 - 它应该匹配的类型。将其视为工会的 Array.prototype.filter

P.S。请避免使用 Number 等构造函数类型,请改用 number

接口Number对应number作为对象,Number作为class对应class构造函数:

interface Number {
    toString(radix?: number): string;
    toFixed(fractionDigits?: number): string;
    toExponential(fractionDigits?: number): string;
    toPrecision(precision?: number): string;
    valueOf(): number;
}

interface NumberConstructor {
    new(value?: any): Number;
    (value?: any): number;
    readonly prototype: Number;
    readonly MAX_VALUE: number;
    readonly MIN_VALUE: number;
    readonly NaN: number;
    readonly NEGATIVE_INFINITY: number;
    readonly POSITIVE_INFINITY: number;
}

declare var Number: NumberConstructor;

更新

取自您共享示例的代码片段:

function reducer(state: State, action: Action): State {
    
    /**
     * Argument of type '{ num: Number; } | { nums: Number[]; }'
     *  is not assignable to parameter of type '{ num: Number; } & { nums: Number[]; }'.
     */
    const newState = actions[action.type](state, action.data);
    return { ...state, ...newState };
}

您收到此错误是因为:

multiple candidates for the same type variable in contra-variant positions causes an intersection type to be inferred.

因此,actions[action.type] 函数的第二个参数是 Actions.

所有参数的交集

Here you have an answer with more examples and here你可以看看我的文章

您可以添加条件语句:

const reducer = (state: State, action: Action): State => {
    if(action.type==="DO_SOMETHING"){
        const newState = actions[action.type](state, action.data); // ok
    }
// ....
}

但这是一个糟糕的解决方案,因为您有很多操作。这不是我们的处理方式。

Here你可以找到类似的例子。

所以你有两个选择,除了前一个。

第一个,只需使用类型断言 - as 并继续。

第二个:


type Builder<A extends { type: PropertyKey, data: any }> = {
    [K in A["type"]]: (state: State, data: Extract<A, { type: K }>["data"]) => State;
};


const reducer = <
    Type extends PropertyKey,
    Data,
    Act extends { type: Type, data: Data },
    Acts extends Builder<Act>
>(actions: Acts) =>
    (state: State, action: Act): State => {
        const newState = actions[action.type](state, action.data);
        return { ...state, ...newState };
    }

您可能已经注意到,我已经推断出 Action 的每个 属性,并在 actionsaction 之间建立了严格的关系。

Full example

P.S。 reducer 是柯里化的,所以不要忘记将它作为 reducer(actions) 传递给 useReducer