You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 04:34:57