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

以下TypeScript数组遍历代码的语法错误是什么?该如何修复?

问题排查与修复方案

现有代码存在的语法错误

  • 保留字误用:case 是 JavaScript/TypeScript 的保留关键字(用于 switch 分支语法),不能作为变量或形参名使用
  • 变量未声明:回调函数内直接打印的 Component、assertion 没有做声明,你没有对传入的元组参数做解构
  • 类型标注非法:元组类型定义 [Component, assertion] 里的 assertion 是值名而非类型,且 Component、Text 未提前定义类型,TS 无法识别

修复后代码

// 提前定义类型,可根据你的实际使用场景调整
type Component = string | typeof Text;
// 示例声明自定义Text组件,如果你有自己的组件实现请替换这段声明
declare const Text: () => JSX.Element;

const txt = 'this is a tes';
// 行首数组加前置分号避免ASI自动分号插入的潜在坑
;[['h1', 'render an h1 tag'], ['p', 'render a p tag'], [Text, 'render Custom component']].forEach(
  // 解构元组,替换非法形参名,标注正确类型
  ([component, assertion]: [Component, string]) => {
    console.log(component, assertion);
  }
);

额外补充

你提到正在学习数组去重,TS 中实现基础数组去重可以直接借助 Set 实现:

const arr = [1,2,2,3,4,4,5];
const uniqueArr = Array.from(new Set(arr)); // 输出 [1,2,3,4,5]

如果是对象数组去重,可以用 Map 存储唯一标识实现:

const objArr = [{id:1, name:'a'}, {id:2, name:'b'}, {id:1, name:'a'}];
const uniqueObjArr = Array.from(new Map(objArr.map(item => [item.id, item])).values());

内容的提问来源于stack exchange,提问作者yavgz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:45:03