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

如何在TypeScript中避免硬编码,根据条件获取接口指定键

如何借助TypeScript特性动态筛选接口中的指定键

首先给出你的接口与枚举(已将注释转为中文):

interface IPropertyPanelInfo {
    isVisible: boolean;
    // 属性面板位置:0-底部 1-右侧
    PositionPropertyPanel: PropertyPanelPosition;
    WidthPercentPropertyPanel: number;
    HeightPercentPropertyPanel: number;
}
export enum PropertyPanelPosition {
    Horizontal, // 对应底部(0)
    Vertical    // 对应右侧(1)
}

你当前通过硬编码键名实现动态键对象:

const mutableObjectKey = panelPosition === PropertyPanelPosition.Horizontal ?
   'WidthPercentPropertyPanel'
   :
   'HeightPercentPropertyPanel';

const newObject = {
 [mutableObjectKey]: 20
}

可行解决方案

完全消除硬编码字符串不现实(运行时必须依赖实际键名),但可以通过TypeScript的类型特性将硬编码集中管理,同时保证类型安全:

方案1:建立枚举与接口键的映射表

通过类型和运行时对象的双向映射,把键名的硬编码集中到一处,后续修改只需维护映射表:

// 类型层面:绑定枚举值到对应接口键
type PositionToKey = {
  [PropertyPanelPosition.Horizontal]: keyof Pick<IPropertyPanelInfo, 'WidthPercentPropertyPanel'>;
  [PropertyPanelPosition.Vertical]: keyof Pick<IPropertyPanelInfo, 'HeightPercentPropertyPanel'>;
};

// 运行时映射对象,与类型严格对齐
const positionToKey: PositionToKey = {
  [PropertyPanelPosition.Horizontal]: 'WidthPercentPropertyPanel',
  [PropertyPanelPosition.Vertical]: 'HeightPercentPropertyPanel'
};

// 使用时直接通过映射获取键
const mutableObjectKey = positionToKey[panelPosition];
const newObject = {
  [mutableObjectKey]: 20
} as { [K in PositionToKey[keyof PositionToKey]]: number };

这样TypeScript会自动校验映射的键是否属于IPropertyPanelInfo,避免拼写错误,同时把硬编码集中到映射对象中,降低维护成本。

方案2:用条件类型推导键类型

通过条件类型在编译时自动推导对应位置的键,同时让函数返回的对象类型更精准:

// 定义条件类型,根据枚举值返回对应接口键
type GetPanelKey<T extends PropertyPanelPosition> = 
  T extends PropertyPanelPosition.Horizontal 
    ? 'WidthPercentPropertyPanel' 
    : 'HeightPercentPropertyPanel';

// 封装成函数,自动推导返回类型
function createPanelConfig<T extends PropertyPanelPosition>(position: T) {
  const key = position === PropertyPanelPosition.Horizontal 
    ? 'WidthPercentPropertyPanel' 
    : 'HeightPercentPropertyPanel' as GetPanelKey<T>;
  return { [key]: 20 } as { [K in GetPanelKey<T>]: number };
}

// 调用示例:返回的对象类型会自动匹配位置
const horizontalConfig = createPanelConfig(PropertyPanelPosition.Horizontal);
// horizontalConfig 类型为 { WidthPercentPropertyPanel: number }
const verticalConfig = createPanelConfig(PropertyPanelPosition.Vertical);
// verticalConfig 类型为 { HeightPercentPropertyPanel: number }

进阶:利用命名规则生成键(仅限规则稳定时)

如果接口键的命名有固定规律(比如都以PercentPropertyPanel结尾),可以用模板字符串类型动态生成:

type PanelKey<T extends PropertyPanelPosition> = 
  T extends PropertyPanelPosition.Horizontal 
    ? `Width${'PercentPropertyPanel'}` 
    : `Height${'PercentPropertyPanel'}`;

但这种方式依赖命名规则的稳定性,不如映射表灵活。

内容的提问来源于stack exchange,提问作者Георгий Барсегян

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:10:48