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

如何在TypeScript中基于typeof对象生成目标类型(修正类型映射)

解决TypeScript类型转换问题

你的InterpolateType类型定义存在几个关键错误,导致无法正确将base转换为GoalType。以下是修正方案和详细说明:

修正后的代码

const base = {
  user: {
    id: { type: 'string' },
    name: { type: 'string' }
  },
  post: {
    id: { type: 'string' },
    title: { type: 'string' },
    published: { type: 'boolean', defaultsTo: false },
    likes: { type: 'number', defaultsTo: 0 }
  }
}

type GoalType = {
  user: {
    id: string
    name: string
  }
  post: {
    id: string
    title: string
    published: boolean
  }
}

// 定义类型映射表,将字符串类型标识对应到TS原生类型
type TypeMap = {
  string: string;
  boolean: boolean;
  number: number;
};

// 修正后的类型转换工具
type InterpolateType<T> = {
  [K1 in keyof T]: {
    [K2 in keyof T[K1]]: TypeMap[T[K1][K2]['type']];
  };
};

// 如果需要过滤掉带有defaultsTo的属性(适配你的GoalType)
type FilterDefaults<T> = {
  [K1 in keyof T]: {
    [K2 in keyof T[K1]]: T[K1][K2] extends { defaultsTo: any } ? never : TypeMap[T[K1][K2]['type']];
  } extends infer O ? { [K in keyof O as O[K] extends never ? never : K]: O[K] } : never;
};

// 完整转换(包含所有属性)
type FoundType = InterpolateType<typeof base>;
// 过滤后的转换(匹配你的GoalType)
type FoundTypeFiltered = FilterDefaults<typeof base>;

关键错误修正说明

  1. 遍历对象键的方式错误
    原代码中[K1 in T]和[K2 in T[K1]]是错误的,因为T是对象类型,需要用keyof T来获取对象的键名集合,正确写法是[K1 in keyof T]和[K2 in keyof T[K1]]。

  2. 类型字段访问错误
    原代码中T[K1]['type']试图访问子对象的type字段,但子对象(如user)本身没有type属性,应该访问子对象中每个属性的type,即T[K1][K2]['type']。

  3. 类型覆盖不完整
    原代码只处理了string和boolean类型,缺少number的映射,使用TypeMap可以统一管理类型映射关系,扩展性更强。

额外说明

如果你需要严格匹配GoalType(即去掉带有defaultsTo的likes属性),可以使用FilterDefaults类型,它会过滤掉包含defaultsTo字段的属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 18:23:23