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

Time:02-28

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.

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?

CodePudding user response:

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

  • Related