简体   繁体   中英

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? . 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:

type CopyFunction<TFn, TR> = TFn extends (...a: infer A) => any ? (...a:A) => TR: never    
type Test22 = CopyFunction<Test, number | Promise<number>>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM