Home > database >  Typescript inference error when returning generics
Typescript inference error when returning generics

Time:01-13

Im having a hard time trying to wrap my head around this.

Typescript Playground

Why does Typescypt infer only some of the return types (check the playground)? what Im doing wrong?

For what I saw, this only happens when using generics.

Thanks in advance!

CodePudding user response:

It's not ignoring them, it's just that CustomError<{}> is enough to cover the string and the number. Both string and 2 are assignable to type {}.

// No errors with either of these
const test: {} = 'Test';
const test2: {} = 2;

So typescript could either say the return type is CustomError<{}> | CustomError<null>, or that it's CustomError<{}> | CustomError<string> | CustomError<number> | CustomError<null>, but since there's no difference between the two, typescript used the shorter one.

Playground Link

If you change the case with an object to a more complex object, such that string and number no longer match with it, then you'll see the number and string appear in the return type:

if(this.randomOperation() == false){
  return new CustomError({ hello: 'world });
}

Playground link

  •  Tags:  
  • Related