gpt4 book ai didi

Typescript 期望将 undefined 作为参数传递

转载 作者:行者123 更新时间:2023-12-05 05:20:12 25 4
gpt4 key购买 nike

typescript :2.4.1

我正在尝试创建一个辅助函数来生成 redux action creators。

我得到的:

interface IAction<T extends string, P = undefined> {
type: T;
payload: P;
}

function createAction<T extends string>(type: T): () => IAction<T, undefined>;
function createAction<T extends string = '', U = undefined, V = {}>(type: T, actionCreator: (payload: U) => V): (payload: U) => IAction<T, V>;
function createAction<T extends string>(type: T, actionCreator?: (payload?: any) => any) {
return (payload: any) => ({
payload,
type,
});
}

enum ActionType {
INCREMENT = 'COUNTER/INCREMENT',
DECREMENT = 'COUNTER/DECREMENT',
ASYNC_INCREMENT = 'COUNTER/ASYNC_INCREMENT',
}

const increment = createAction(ActionType.INCREMENT, () => ({ amount: 1 }));
const incrementBy = createAction(ActionType.INCREMENT, (amount: number) => amount);

在这个例子中,我希望 increment 是一个接受 0 个参数的函数,而 incrementBy 正好接受 1(一个 number) .

incrementBy 按预期工作,但 Typescript 在调用 increment()(不带参数)时抛出此错误:

[ts] Expected 1 arguments, but got 0;

尝试以我调用 incrementBy 的方式调用它,例如increment(42),我得到这个错误:

[ts] Argument of type '42' is not assignable to parameter of type 'undefined';

这有效:increment(undefined)

有办法解决这个问题吗?

最佳答案

您应该简单地创建另一个重载,它表示它将返回一个没有参数的函数,而不是一个将 undefined 作为唯一参数的函数。

function createAction<T extends string>(type: T): () => IAction<T, undefined>;
function createAction<T extends string, V>(type: T, actionCreator: () => V): () => IAction<T, V>;
function createAction<T extends string, U, V>(type: T, actionCreator: (payload: U) => V): (payload: U) => IAction<T, V>;
function createAction<T extends string, U, V>(type: T, actionCreator?: (payload: U) => V): (payload: U) => IAction<T, V> {
return (payload: any) => ({
payload,
type,
});
}

但是,您的实现似乎对传递的函数没有任何作用。您可能想要这样做:

function createAction<T extends string>(type: T): () => IAction<T, undefined>;
function createAction<T extends string, V>(type: T, actionCreator: () => V): () => IAction<T, V>;
function createAction<T extends string, U, V>(type: T, actionCreator: (payload: U) => V): (payload: U) => IAction<T, V>;
function createAction<T extends string, U, V>(type: T, actionCreator?: (payload: U) => V): (payload: U) => IAction<T, V> {
if (actionCreator) {
return (payload: U) => ({
payload: actionCreator(payload),
type,
});
} else {
return () => ({
payload: undefined,
type
});
}
}

关于Typescript 期望将 undefined 作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44792179/

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