如何用Dexie.js过滤排序虚拟列?TypeScript类型问题求助
解决方案
1. 避免对象突变:用map替代modify
modify会直接修改原对象,存在副作用风险。更安全的做法是用map创建包含match属性的新对象,完全保留原数据的完整性:
const searchWords = ['word1', 'word2', 'word3']; const result = query .filter(home => searchWords.some(word => home.comment.includes(word))) .map(home => { const matchCount = searchWords.filter(word => home.comment.includes(word)).length; return { ...home, match: matchCount / searchWords.length }; });
2. 让TypeScript识别match属性
有两种简单方式处理类型:
- 定义新类型:显式声明包含
match的扩展类型
type HomeWithMatch = Home & { match: number }; const result: HomeWithMatch[] = query // ... 上述filter和map逻辑
- 自动推导类型:TypeScript会自动识别
map返回的新对象类型,也可以省略显式类型声明,让编译器自行推断。
3. 按match值降序排序
在map之后链式调用sort方法即可:
const sortedResult = query .filter(home => searchWords.some(word => home.comment.includes(word))) .map(home => { const matchCount = searchWords.filter(word => home.comment.includes(word)).length; return { ...home, match: matchCount / searchWords.length }; }) .sort((a, b) => b.match - a.match);
额外优化:避免重复计算
上述代码中home.comment.includes(word)被执行了两次(filter和map各一次),可以提前计算匹配的关键词数组,提升效率:
const sortedResult = query .map(home => { const matchedWords = searchWords.filter(word => home.comment.includes(word)); return { ...home, match: matchedWords.length / searchWords.length }; }) .filter(home => home.match > 0) // 过滤完全不匹配的项 .sort((a, b) => b.match - a.match);
内容的提问来源于stack exchange,提问作者Francesco Meli
相关产品推荐
相关产品推荐

