Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to infer return type of a generic function with default types

Given the following code:

declare function test<A = number, B = string>(a: A, b: B): { a: A, b: B }

type T1 = ReturnType<typeof test>         // { a: unknown; b: unknown }
type T2 = ReturnType<typeof test<number>> // { a: number; b: string }

Why can’t TS infer T1 correctly? Is it a bug? Are there any workarounds besides T2?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Typescript infers the type unknown correctly, since the types of A and B are not defined as long as the function is not called with arguments. You must define the types with extends like this:

declare function test<A extends number = number, B extends string = string>(a: A, b: B): { a: A, b: B }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading