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

如何用TypeScript泛型将类型属性转为自身或自身数组类型?

TypeScript泛型实现类型转换方案

要实现将对象类型的每个属性转换为「原类型 | 原类型数组」的泛型,可以利用TypeScript的映射类型完成:

type Transformed<T> = {
  [K in keyof T]: T[K] | T[K][]
}

测试验证

// 原始类型
type Car = {
  color: string;
  speed: number;
}

// 转换后的类型
type TransformedCar = Transformed<Car>

此时TransformedCar的类型结构完全符合需求:

{
  color: string | string[];
  speed: number | number[];
}

原理说明

  • [K in keyof T]:遍历传入类型T的所有属性键;
  • T[K] | T[K][]:将每个属性的类型替换为「原类型」和「原类型数组」的联合类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 07:32:04