简体   繁体   中英

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皮棉错误

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

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

Typescript playground Link Sample Code

The reason for this error is that names might be either an array of NameObj ( NameObj[] ) or an array of string s ( string[] ), and while both provide a function find , NameObj[].find returns NameObj | undefined NameObj | undefined and string[].find returns string | undefined 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM