可选的通用参数

时间:2018-03-02 12:33:26

标签: typescript

我有以下功能

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的约束。这可能吗?

1 个答案:

答案 0 :(得分: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> {
...
}