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

如何在TypeScript中定义MyType验证子数组元素类型一致?

如何定义MyType确保数组中每个子数组元素类型统一

要实现需求里的约束——让数组的每个子数组内部元素类型一致,不同子数组可以是不同类型,但子数组不能混放多种类型元素——可以通过TypeScript的条件类型来定义MyType:

实现代码

// 判断数组是否为同构数组(元素类型单一)
type IsHomogeneousArray<T extends readonly any[]> = 
  T[number] extends infer U ? (T extends readonly U[] ? true : false) : false;

// 定义MyType:仅允许元素为同构数组的数组
type MyType = Array<
  T extends readonly any[] ? IsHomogeneousArray<T> extends true ? T : never : never
>;

测试示例

const array1: MyType = [["foo", "bar"], [42, 42], [true, false]]; // 正常通过,每个子数组元素类型统一
const array2: MyType = [["foo", "bar"], [42, 42], [true, "false"]]; // 抛出TS错误,第三个子数组混有boolean和string类型

扩展说明

这个定义支持任意类型的同构数组,包括自定义类型:

type User = { name: string };
const array3: MyType = [[{name: "Alice"}, {name: "Bob"}], [100, 200]]; // 正常通过
const array4: MyType = [[{name: "Alice"}, 100]]; // 抛出TS错误,子数组混有自定义类型和number类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 05:15:09