TypeScript中将二元数组转换为带x、y键的坐标对象的最优方法
实现方案及问题修正
原有代码问题
- reduce生成的对象键为数组索引
0/1,不符合x/y的键名要求 - 转换后的
converted变量未赋值给返回值,函数永远返回默认的{x: 0, y: 0} - 入参未做长度校验,也没有用TS类型限制数组必须为2位数字,存在类型安全隐患
最优实现(类型安全+最高性能)
需求是固定转换2位数字数组,不需要用reduce这类遍历方法,直接索引取值是性能最好、逻辑最简洁的方案:
interface Coordinates { x: number; y: number; } // 用TS元组限制入参必须为恰好2位的数字数组 function getAnObjectOfnum(arr: [number, number]): Coordinates { return { x: arr[0], y: arr[1] }; } console.log(getAnObjectOfnum([7, 9])); // 输出 {x:7, y:9}
兼容多入参形式的扩展实现
如果你需要同时支持「传2位数字数组」和「传两个单独的x、y参数」,可以保留重载逻辑,修正后代码如下:
interface Coordinates { x: number; y: number; } function getAnObjectOfnum(arr: [number, number]): Coordinates; function getAnObjectOfnum(x: number, y: number): Coordinates; function getAnObjectOfnum(arg1: unknown, arg2?: unknown): Coordinates { if (Array.isArray(arg1) && arg1.length === 2 && typeof arg1[0] === 'number' && typeof arg1[1] === 'number') { return { x: arg1[0], y: arg1[1] }; } if (typeof arg1 === 'number' && typeof arg2 === 'number') { return { x: arg1, y: arg2 }; } throw new Error('参数非法,请传入长度为2的数字数组,或两个单独的数字参数'); } console.log(getAnObjectOfnum([7, 9])); // 输出 {x:7, y:9} console.log(getAnObjectOfnum(7, 9)); // 输出 {x:7, y:9}
内容的提问来源于stack exchange,提问作者user16911633
相关产品推荐
相关产品推荐

