gpt4 book ai didi

typescript - 有没有更好的方法来告诉 typescript "data"是什么类型?

转载 作者:行者123 更新时间:2023-12-02 01:59:14 25 4
gpt4 key购买 nike

我正在遵循 React 的操作/ 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 联合类型中列出的所有操作类型,并在尝试分派(dispatch)操作时提供类型安全。当尝试访问 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我一直在用它来测试这一切。

最佳答案

你们非常接近。

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

Action['data'] 应该已与 key 属性绑定(bind)。

请参阅此示例:

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

由于我们正在迭代 types 属性,因此我使用了 Type 而不是 key

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

附注请避免使用 Number 等构造函数类型,而使用 number

接口(interface)Number对应作为对象的number,作为类的Number对应类构造函数:

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您有更多示例的答案和 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

附注reducer 是柯里化(Currying)的,所以不要忘记将它作为 reducer(actions) 传递给 useReducer

关于typescript - 有没有更好的方法来告诉 typescript "data"是什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69201083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com