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

232
Views
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 answers
Answer question

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 Report
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!