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

237
Visualizações
Typescript function param with interface object array & string array

I am trying to create a Typescript function that have a parameter with an interface of Object[] or string[].

interface NameObj {
    val: string
}
const myFunc = function(names : NameObj[] | string[], toFind: string) {
    return names.find(name => name.val === toFind || name === toFind );
}

const list = ['app', 'test', 'ben']

console.log(myFunc(list, 'ben'))

Lint Error Lint Error

but I am getting an Lint error in find(name => ...) of

Parameter 'name' implicitly has an 'any' type.'

Typescript playground Link Sample Code

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The reason for this error is that names might be either an array of NameObj (NameObj[]) or an array of strings (string[]), and while both provide a function find, NameObj[].find returns NameObj | undefined and string[].find returns string | undefined, so the compiler don't now which type to use.

The are different ways to handle this. I would prefer the use of generics. This way you tell the compiler that we can input either NameObj[] or string, and whichever it is, that's also the type returned.

const myFunc = function<T extends NameObj | string>(names : T[], toFind: string) {
    return names.find(name => typeof name === "object" ? name.val === toFind : name === toFind);
}

In the above code I also changed the function to name => typeof name === "object" ? name.val === toFind : name === toFind . With your previous implementation, you get an error since name might be a string and thus name.val is invalid. This checks the type first.

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