Reputation: 345
The below code gives the following error on
"[i]" in "if (i == ingredients[i])"
error:
element implicitly has an 'any' type because index expression is not of type 'number'
code:
let ingredients = ["ham","onion","tomato"];
let sandwichhas = function(ingredients:string[]){
for(let i of ingredients){
if (i == ingredients[i]){
return true;
}
}
}
if (snd("tomato") && snd("onion")){
console.log("Sandwich has tomatos and onions")
}else {
console.log("Sandwich has no tomatos and onions")
}
And in the if statement below there's an error saying:
Argument of type '"tomato"' is not assignable to parameter of type 'string[]'.
Argument of type '"onion"' is not assignable to parameter of type 'string[]'.
What is the workaround for this?
Upvotes: 1
Views: 525
Reputation: 28708
I suggest you modify your code to the following:
let ingredients = ["ham", "onion", "tomato"];
let snd = function (item) {
for (let i = 0; i <= ingredients.length; i++) {
if (item === ingredients[i]) {
return true;
}
}
}
if (snd("tomato") && snd("onion")) {
console.log("Sandwich has tomatos and onions")
} else {
console.log("Sandwich has no tomatos and onions")
}
The function argument was set to ingredient, instead of a string parameter that you pass, such as "tomato" and "onion". They are of type "string", it is ingredient[], an array fro now. i in the iteration was used mistakenly also.
Upvotes: 1