我想按id过滤

I want to filter by id

我想按标题和 ID 过滤我的歌曲数组,但打字稿抛出错误 属性 tolowercase() 不退出类型编号

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;
}

按标题过滤效果很好,但按 id 一直给我这个错误

"属性 'toLowerCase' 类型不存在 'number'"

因此,如果错误提示类型编号不存在 toLowerCase,这意味着类型编号不能为“toLowerCase”,因为该编号不是字符串。如果您的 ID 包含任何字母,请将类型更改为字符串。

我觉得错误很明显,项目被动态转换为数字类型。尝试通过附加 .toString()

将其转换为字符串

而不是

return item.title.toLowerCase()...

改成这样

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

或者你可以用三元来判断是不是字符串类型

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

如果 id 存储为数字,则 .toLowerCase() 将不起作用,因为它仅适用于字符串,您需要将 id 字符串化

 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;
}