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

TypeScript中如何通过类型的键获取对应值并转换为负数

解决方案

你当前的问题核心是:TypeScript的类型仅存在于编译阶段,编译完成后会被完全擦除,所以单纯靠类型testingNumbers无法在运行时获取对应的值。必须搭配一个运行时对象来存储实际数据,再基于这个对象生成类型,既保证类型安全,又能实现你要的功能。

完整实现代码

首先定义运行时对象并生成对应类型(替代你原来的纯类型定义):

// 运行时可用的实际数据对象
export const testingNumbersObj = {
  zero: '0px',
  xxxs: '4px',
  xxs: '8px',
  xs: '12px',
  s: '16px',
  m: '24px',
  l: '32px',
  xl: '40px',
  xxl: '64px',
  xxxl: '80px',
} as const;

// 基于对象自动生成类型,无需手动重复定义
export type testingNumbers = typeof testingNumbersObj;
export type testingNumbersKeys = keyof testingNumbers;
export type testingNumbersValues = testingNumbers[testingNumbersKeys];

然后实现getNegativeNumber函数:

const getNegativeNumber = (marginKey: testingNumbersKeys) => {
  // 从运行时对象中获取对应的值字符串
  const valueStr = testingNumbersObj[marginKey];
  // 提取字符串中的数字部分并转为数值
  const num = parseInt(valueStr, 10);
  // 返回负数(0的情况保持0)
  return num === 0 ? 0 : -num;
};

关键说明

  • as const:让TypeScript将对象的属性值推断为字面量类型(比如'0px'而非宽泛的string),确保testingNumbers类型能精准约束键值对。
  • 运行时对象是核心:类型无法提供运行时数据,必须通过实际对象来获取对应键的值。
  • 数值转换:用parseInt提取px字符串中的数字,再转为负数返回。

内容的提问来源于stack exchange,提问作者A.Martin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:05:26