TypeScript数组去重:将JS去重代码转换为TS实现求助
解决TypeScript数组去重的问题
嘿,别担心,作为TypeScript新手遇到这种类型相关的小困惑太正常啦!我帮你把这段JavaScript代码转换成完全等价的TypeScript版本,同时解释一下你遇到的“空对象”问题~
与原逻辑完全一致的TypeScript版本
你遇到的问题其实是TypeScript的类型推断导致的:当你直接写let unique = {}时,TS会自动推断它的类型为{}(也就是没有任何属性的空对象),之后给它添加属性时就会报错。只需要给这个对象加上明确的类型标注就能解决:
const names = ['John', 'Paul', 'George', 'Ringo', 'John']; function removeDups(names: string[]): string[] { // 用Record<string, boolean>标注:键是字符串,值是布尔值的对象 let unique: Record<string, boolean> = {}; names.forEach(function(i) { if (!unique[i]) { unique[i] = true; } }); return Object.keys(unique); } console.log(removeDups(names)); // 输出: ['John', 'Paul', 'George', 'Ringo']
更简洁的TypeScript实现
如果你想让代码更简洁,TypeScript完全支持ES6的Set语法,它天生就能帮你去除数组重复项,代码会短很多,输出结果和你原来的代码完全一致:
const names = ['John', 'Paul', 'George', 'Ringo', 'John']; function removeDups(names: string[]): string[] { return [...new Set(names)]; } console.log(removeDups(names)); // 输出: ['John', 'Paul', 'George', 'Ringo']
这样两种写法都能满足你的需求,第一种完全复刻了你原来的逻辑,第二种是更现代的写法,看你个人习惯选择就好~
内容的提问来源于stack exchange,提问作者Nando
相关产品推荐
相关产品推荐

