Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

231
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda