Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

136
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda