Why Typescript prioritizing type inferring over generic type with default?

Viewed 46

Do you have an explanation why TS doesn't infer the string type in the first example? Despite I used string as a default for the generic T in the bar function? Thanks

The error (in example 1):

Argument of type 'string | number' is not assignable to parameter of type 'string | undefined'. Type 'number' is not assignable to type 'string | undefined'.ts(2345)

// Example 1 (has error)

const baz = (a: unknown) => a;

const bar = <T extends string | number = string>(): T => {
  return baz('some_value') as T;
};

const foo = (str?: string) => `${str} is string`;

// Error!!

foo(bar());

I've two options for a solution but I'm not sure why they work:

  • extracting the bar() call into constant (example 2)
  • removing the options operator from str (example 3)
// Example 2 (no error)

const baz = (a: unknown) => a;

const bar = <T extends string | number = string>(): T => {
  return baz('some_value') as T;
};

const foo = (str?: string) => `${str} is string`;

const barResult = bar();
foo(barResult);

Remove the ?:

// Example 3 (no error)

const baz = (a: unknown) => a;

const bar = <T extends string | number = string>(): T => {
  return baz('some_value') as T;
};

const foo = (str: string) => `${str} is string`;

foo(bar());
0 Answers
Related