TransWikia.com

I want to filter by id

Stack Overflow Asked by Manunyi on December 18, 2021

I want to filter my array of song by title and id but typescript throwing me error that property tolowercase() does not exit on type number

public querySongs() {
    let    song: Song[] = [];
    song =  this.song.filter((item) => {
        return item.title.toLowerCase().indexOf(this.queryText.toLowerCase()) > -1 ||
        item.id.toLowerCase().indexOf(this.queryText.toLowerCase()) > -1
    });
    this.song = song;
}

filtering by title works fine but by id keeps given me this error

"Property ‘toLowerCase’ does not exist on type ‘number’"

3 Answers

If the id's are stored as numbers then .toLowerCase() won't work because that only works on string's you need to stringify the id's

 public querySongs() {
    let    song: Song[] = [];
       song =  this.song.filter((item) => { return item.title.toLowerCase().indexOf(this.queryText.toLowerCase()) > -1 ||
            item.id.stringify().toLowerCase().indexOf(this.queryText.toLowerCase()) > -1
    });
        this.song = song;
}

Answered by swift gaming on December 18, 2021

I think the error is clear enough, the item is dynamically cast as number type. Try to cast it to string by appending .toString()

Instead of

return item.title.toLowerCase()...

Change it like this

return item.title.toString().toLowerCase()

or you can use ternary to identify whether it's string type or not

return typeof item.title === 'string' ? item.title.toLowerCase() : item.title

Answered by Fahim Bagar on December 18, 2021

So if error says that the toLowerCase not exist on type number this means that type number can't be "toLowerCase" cuz the number is not a string. Change type to string if your id contains any letters.

Answered by programmer on December 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP