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

Two generic functions, both passed in the same parameter but evaluated differently, why

I have the following code of generic functions:

type Bar<T> = {bar: T}

function test1<T>(arg: T extends {foo: number} ? T : never): void {}
function test3<T>(arg: T extends {foo: number} ? Bar<T> : never): void {}

When I call them:

test1({foo: 23}); // Good!
test3({foo: 23}); // Type 'number' is not assignable to type 'never'.

I get confused, I mean shouldn’t both test1(...) and test3(...) evaluating type condition of arg: T extends {foo: number} to be true? I mean they have exactly the same parameters passed into the functions & they have the same evaluation condition for types.

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

In other words, Why test3({foo:23}) falls into the never value for type instead of Bar<T>? I also expect the test3({foo:23}) fail but with an error message that says expecting {bar: number}, why error messages instead complains the never side?

>Solution :

I get confused, I mean shouldn’t both test1(...) and test3(...) evaluating type condition of arg: T extends {foo: number} to be true?

In test3, you’ve said the argument would be Bar<T> when T extends {foo: number}. So it would expect {bar: {foo: number}} since Bar<T> is {bar: T}. Since what you’re passing it can’t match Bar<T>, never is used.

If you pass it what you’ve said it should receive, it works just fine:

test3({bar: {foo: 23}}); // Good!

Playground link

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