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

如何编写兼具类型安全的对象键通用处理函数?

解决方案

核心问题是TypeScript处理联合类型分支时,无法自动推断每个分支的精确类型,导致data的类型被错误合并为跨分支的联合,与原类型不兼容。通过泛型精确追踪输入的联合成员类型即可解决:

type FirstType = {
  type: 'first';
};

type SecondType = {
  type: 'second';
  data: {
    label: string;
  };
};

type ThirdType = {
  type: 'third';
  data: {
    url: string;
  };
};

type SomeUnion = FirstType | SecondType | ThirdType;

const objectKeys = <T extends Record<string, unknown>>(obj: T): Array<keyof T> =>
  Object.keys(obj) as Array<keyof T>;

const replacer = (data: string): string => data.replace('http://', 'https://');

// 用泛型约束追踪输入的联合成员类型
function transformValue<T extends SomeUnion>(value: T): T {
  if ('data' in value) {
    const transformedData = objectKeys(value.data).reduce((acc, key) => {
      return {
        ...acc,
        [key]: replacer(value.data[key] as string)
      };
    }, {} as typeof value.data); // 明确初始值为当前value的data类型
    return {
      ...value,
      data: transformedData
    } as T;
  }
  return value;
}

// 保留原有count逻辑
const processor = (data: SomeUnion[]): SomeUnion[] =>
  data.reduce(
    (acc, value) => ({
      count: acc.count + 1,
      newData: [...acc.newData, transformValue(value)],
    }),
    {
      count: 0,
      newData: [] as SomeUnion[],
    }
  ).newData;

关键改动说明:

  • 泛型T extends SomeUnion:让函数精确识别输入的联合成员类型,返回类型与输入严格一致,避免类型拓宽。
  • typeof value.data约束:在reduce中明确初始值类型为当前输入对象的data类型,防止TypeScript将其推断为跨分支的联合类型。
  • 类型断言as T:明确告知TypeScript处理后的对象符合输入的T类型,解决分支返回的类型不匹配报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:53:13