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

89
Visualizações
Generic type is type script
function identity<String>(arg: String): String {
  return arg;
}
 
let myIdentity = identity([2]);
console.log()

Hi could someone help me to understand why this doesn't throw any type error even if i am passing a array of numbers ?

  1. Is it because the type is "String" instead of "string" , which looks for objects than primitive ?
  2. If answer is "yes" , if i change everything to string i get error saying string is never used
function identity<string>(arg: string): string {
  return arg;
}
 
let myIdentity = identity([2]);
console.log(myIdentity )

'string' is declared but its value is never read.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are shadowing the builtin types String and string by using their names as your generic parameter. Just use a parameter name that is not a built-in to solve it:

TS Playground link

function identity<T extends string>(value: T): T {
  return value;
}
 
identity([2]); // error [2] doesn't extend string
identity('2'); // ok

If you want a generic identity function without any kind of constraint, you can use an unconstrained type parameter:

TS Playground link

function identity<T>(value: T): T {
  return value;
}
 
const numberArrayValue = identity([2]); // number[]
const objectValue = identity({b: 2}); // { b: number; }
const stringLiteralValue = identity('2'); // "2"
const numberLiteralValue = identity(2); // 2
about 4 years ago · Juan Pablo Isaza Relatório
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