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

如何实现自动为交叉类型属性添加DeviceInfo的TS工具类型

解决方案

你需要用映射类型遍历原类型的每个属性,将单个属性的类型与DeviceInfo交叉,而非把整个类型和DeviceInfo交叉。正确的WithDeviceInfo工具类型实现如下:

type WithDeviceInfo<T> = {
  [K in keyof T]: T[K] & DeviceInfo;
};

完整使用示例

// 补全示例基础类型
type SomeType = { value: number };
type SomeOtherType = { name: string };
type DifferentType = { id: string };
type AnotherDifferentType = { active: boolean };

// 原类型定义
type A = {
  'a-first-key': SomeType
  'a-second-key': SomeOtherType
}

type B = {
  'b-first-key': DifferentType
  'b-second-key': AnotherDifferentType
}

type DeviceInfo = {
  os: string
  manufacturer: string
}

// 应用工具类型处理交叉类型
type Intersection = WithDeviceInfo<A & B>

// 泛型函数可正常使用,属性类型已自动包含DeviceInfo
function genericFunction<T extends keyof Intersection>(
  key: T,
  data: Intersection[T]
) {
  // 示例:访问DeviceInfo属性不会报错
  console.log(data.os, data.manufacturer);
}

原写法错误原因

你之前的Record<keyof T, T & DeviceInfo>会把每个属性的类型设置为整个原类型T与DeviceInfo的交叉,而非对应属性自身类型与DeviceInfo交叉。比如a-first-key的类型会变成(A & B) & DeviceInfo,完全不符合需求。

而映射类型[K in keyof T]: T[K] & DeviceInfo会逐个遍历T的每个键K,取原属性类型T[K]后与DeviceInfo交叉,精准实现给每个属性添加DeviceInfo的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:01:55