Vue+TypeScript调用category.sort()报错:Property 'sort'不存在于该类型
问题原因
你调用category.sort()报错是因为**category是单个分类名称(字符串字面量类型,比如shoes4men),不是数组**,而sort()是数组的专属方法,自然不存在于单个字符串上。你能正常操作count是因为它是对象的数值属性,TypeScript能正确推断其类型为number,所以可以调用toLocaleString()这类数字方法。
解决方案
要实现分类排序,得先把对象的所有分类键转换为数组,排序后再遍历。以下是具体修改:
1. 处理排序逻辑(脚本部分)
const products = { "shoes": { "shoes4men": 1402, "shoes4women": 99, "shoes4kids": 3000, "shoes4athletes": 57 } }; // 假设你已定义product变量,比如const product = 'shoes' // 将分类键转为数组并指定类型,避免TS类型报错 const sortedCategories = Object.keys(products[product]) as Array<keyof typeof products['shoes']>; // 可选:按分类名称字符串升序排序 sortedCategories.sort(); // 或者按商品数量从高到低排序 // sortedCategories.sort((a, b) => products[product][b] - products[product][a]);
2. 修改模板遍历
<div v-for="category in sortedCategories" :key="category"> <div>{{ category }}</div> <div>{{ products[product][category].toLocaleString() }}</div> </div>
额外说明
Object.keys()默认返回string[],用as Array<keyof typeof products['shoes']>是为了让TypeScript识别出数组元素是具体的分类字面量类型,避免后续访问products[product][category]时出现类型报错。- 如果只需要按分类名称排序,直接调用
sortedCategories.sort()即可;如果要按商品数量排序,用注释里的自定义排序逻辑即可。
内容的提问来源于stack exchange,提问作者Boq7
相关产品推荐
相关产品推荐

