可选的通用参数

问题描述 投票:1回答:1

我有以下功能

export function createAsyncAction<R, S>(selector: Select<S>, call: CallApi<R, S>, config: Config<R, S>): ApiAction<R, S> {
    return {
        type: '@api/ACTION',
        payload: {
            call,
            selector,
            ...config
        }
    }
};

为此自动推断通用参数RS。我想保留这些可选项并添加一些更通用的参数,如下所示:

export function createAsyncAction<A, B, C, R, S>(selector: Select<S>, call: CallApi<R, S>, config: Config<A, B, C, R, S>): ApiAction<R, S> {
    return {
        type: '@api/ACTION',
        payload: {
            call,
            selector,
            ...config
        }
    }
};

这样我才能做到

createAsyncAction<RequestType, RequestSucces, RequestFailure>(...)

同时仍然自动执行RS的约束。这可能吗?

typescript
1个回答
3
投票

根据您的需要,您可以执行以下两项操作之一:

为泛型参数添加默认类型

export function createAsyncAction<R = {}, S = {}, A = {}, B = {}, C = {}>(selector: Select<S>, call: CallApi<R, S>, config: Config<A, B, C, R, S>): ApiAction<R, S> {
    return {
        type: '@api/ACTION',
        payload: {
            call,
            selector,
            ...config
        }
    }
};
// Usage
createAsyncAction<RequestType, RequestSucces>()
createAsyncAction<RequestType, RequestSucces, ImplementationForA>()

为函数添加几个重载

这将要求您在没有额外类型的情况下表达您的函数签名,您需要决定每个签名的外观。例如:

export function createAsyncAction<R, S>(selector: Select<S>, call: CallApi<R, S>): ApiAction<any, any> 
export function createAsyncAction<A, B, C, R, S>(selector: Select<S>, call: CallApi<R, S>, config?: Config<A, B, C, R, S>): ApiAction<R, S>
// Implementation siganture, not public 
export function createAsyncAction<A, B, C, R, S>(selector: Select<S>, call: CallApi<R, S>, config?: Config<A, B, C, R, S>): ApiAction<R, S> {
...
}
© www.soinside.com 2019 - 2024. All rights reserved.