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

如何仅定义一次关键字,实现TypeScript接口继承与数据提取?

只定义一次继承关键字的解决方案

你可以通过TypeScript的const断言结合类型推导,实现关键字只定义一次,同时满足类型定义和运行时逻辑的需求。具体修改如下:

完整代码示例

interface IPrimaryType {
  key1: string;
  key2: string;
  key3: string;
  key4: string;
  key5: string;
  key6: string;
  key7: string;
}

interface ISecondaryType {
  thisDoesntMatter: string;
}

interface ITertiaryType {
  thisDoesntMatter: string;
}

// 只在这里定义一次关键字,用as const断言锁定字面量类型
const inheritedKeys = ['key1', 'key2', 'key3', 'key4', 'key5'] as const;
// 从数组推导联合类型,用于Pick操作
type InheritedKeys = typeof inheritedKeys[number];

// 用推导出来的类型替代手动写的联合关键字
interface IInheritedType extends Pick<IPrimaryType, InheritedKeys> {
  secondaryData: ISecondaryType;
  tirtiaryData?: ITertiaryType | null;
}

const primaryObj = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3',
  key4: 'value4',
  key5: 'value5',
  key6: 'value6',
  key7: 'value7',
};
const secondaryData = { thisDoesntMatter: '' };
const tirtiaryData = { thisDoesntMatter: '' };

// reduce时直接使用推导的类型,无需any断言
let inheritedObj = inheritedKeys.reduce(
  (acc, key: InheritedKeys) => ({ ...acc, [key]: primaryObj[key] }),
  {} as Pick<IPrimaryType, InheritedKeys>
);

// 合并扩展属性
inheritedObj = {
  ...inheritedObj,
  secondaryData,
  tirtiaryData
};

关键说明

  • as const:将数组的元素类型锁定为具体的字面量(如'key1'而非string),确保TypeScript能推导精确的联合类型。
  • typeof inheritedKeys[number]:从字面量数组中提取所有元素的联合类型,作为Pick<IPrimaryType, ...>的第二个参数,避免手动重复编写关键字。
  • 类型安全:后续修改关键字时,只需更新inheritedKeys数组,类型定义和运行时逻辑会自动同步,同时TypeScript会在关键字不匹配IPrimaryType属性时给出错误提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:32:52