Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
Why Typescript prioritizing type inferring over generic type with default?

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());
about 4 years ago ยท Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!