0

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

4
  • 1
    You need to narrow the type (typeof name === 'string' ? name : name.val) === toFind playground Commented Jun 5, 2022 at 13:41
  • 1
    You will need a type guards, eg. 'val ' in name ? name.val === tofind : name === tofind Commented Jun 5, 2022 at 13:41
  • Your types do not have both the property val, that is why typescript assume it needs to be any. Commented Jun 5, 2022 at 13:41
  • What about this: stackoverflow.com/questions/49510832/… Commented Jun 5, 2022 at 13:44

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.