[英]Typescript - Change function return type
I want to override a function changing its return type. 我想重写一个更改其返回类型的函数。 I've found this approach, TypeScript: How to wrap a function, changing its return type? 我发现了这种方法, TypeScript:如何包装函数,更改其返回类型? . 。 However, I'd like a more generic one. 但是,我想要一个更通用的。
type Test = (
a: string,
b: string,
c: number,
) => string | Promise<string>;
type Test2 = (
a: string,
b: string,
c: number,
) => number | Promise<number>;
What I expect is something like: 我期望的是这样的:
// CopyFunction(Function, Return)
type Test2 = CopyFunction(Test, number | Promise<number>);
You can make a type that uses conditional types and tuples in rest parameter to do what you want: 您可以创建一个在rest参数中使用条件类型和元组的类型,以执行所需的操作:
type CopyFunction<TFn, TR> = TFn extends (...a: infer A) => any ? (...a:A) => TR: never
type Test22 = CopyFunction<Test, number | Promise<number>>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.