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

TypeScript如何实现将对象类型所有属性批量转为string类型

实现方案

你需要的AllString<T>泛型可以直接通过TypeScript的映射类型实现,不需要依赖内置工具类型,写法非常简洁:

type AllString<T> = {
  [K in keyof T]: string
}

实现逻辑说明

  • keyof T会获取传入对象类型T的所有公开属性名,组成字符串/数字/符号字面量联合类型
  • [K in keyof T]是映射类型的固定语法,代表遍历上一步拿到的所有属性名
  • 遍历过程中直接将每个属性的类型统一指定为string,同时会自动保留原属性的可选、只读等修饰符

效果验证

用你给出的示例类型测试,生成的类型和目标类型完全一致:

type ExampleType = {
  one: string
  two: boolean
  three: 'A' | 'Union'
}

// 校验生成的类型
type ExampleStringType = AllString<ExampleType>
// 等价于 { one: string; two: string; three: string }

// 赋值时完全符合类型要求
const value: AllString<ExampleType> = {
  one: "string",
  two: "string",
  three: "string"
}

如果你不需要保留原属性的可选修饰符,可以把写法改成[K in keyof T]-?: string,会强制所有属性变为必填的string类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 20:24:28