使用嵌套通用参数

时间:2018-05-22 20:15:19

标签: typescript types

我希望能够定义一个接受泛型参数的类型(它本身扩展了一个带有2个泛型参数的类型)并使用嵌套的泛型参数定义其约束。

// Boiler plate for example setup:
type NodeCallback<T> = (err?: Error | void, result?: T) => void
type Handler<I, R> = (event: I, callback: NodeCallback<R>) => void
type StrToNumHandler = Handler<string, number>

// I end up having to do this:
type WorkaroundAsyncHandler<T extends Handler<I, R>, I, R> = (event: I) => Promise<R>
type WorkaroundStrToNumHandler = WorkaroundAsyncHandler<StrToNumHandler, string, number>

// I'd like to be able to just write this:
type AsyncHandler<T extends Handler<I, R>> = (event: I) => Promise<R> // This is a compiler error. Not sure how to write this in a valid way.
type AsyncStrToNumHandler = AsyncHandler<StrToNumHandler> // This is the line I'd ultimately like to write

我编译的解决方法,但如果我提供IR的值,则提供Handler没有任何价值,我想要能够做到。

1 个答案:

答案 0 :(得分:1)

你可以与c onditional types and type inference in conditional types

非常接近
type AsyncHandler<T> = T extends Handler<infer I, infer R> ? 
                             (event: I) => Promise<R> 
                          :  never
;

type AsyncStrToNumHandler = AsyncHandler<StrToNumHandler> 
// inferred as AsyncStrToNumHandler = (event: string) => Promise<number>

缺点是,即使T实际上不是Handler,您的类型别名也应提供某种类型。通常的解决方案是返回never类型。但是,在收到never类型时,使用此类别名的代码在编译时可能会出现意外行为。