简体   繁体   中英

Removing Items from an Array in Typescript Using .filter() - Immutable Pattern

I am trying to remove item from array Using.filter() - Immutable Pattern

const drinks = ['Cola', 'Lemonade', 'Coffee', 'Water'];
const id = 'Coffee';
const idx = drinks.indexOf(id);
const removedDrink = drinks[idx];
const filteredDrinks = drinks.filter((drink, index) => drink !== idx);

But the problem I have that I have error like this

const idx: number This condition will always return 'true' since the types 'string' and 'number' have no overlap

With .filter 's callback, the first argument is the value being iterated over, and the second argument is the index being iterated over. TypeScript is correctly warning you that comparing the idx - a number - to one of the array elements - a string - doesn't make sense.

indexOf is completely superfluous anyway here. Just use

const drinks = ['Cola', 'Lemonade', 'Coffee', 'Water'];
const id = 'Coffee';
const filteredDrinks = drinks.filter(drink => drink !== id);

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