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

TypeScript中如何复用同类型并为不同函数重命名属性?

解决TypeScript接口属性重命名复用的问题

你写的CalculatePercentage函数里,参数解构用了Percentage: percent,但你定义的Prices接口根本没有Percentage这个属性,TypeScript会严格校验类型结构,所以才会报错。下面给两种针对性的解决方案:

方案1:仅在函数内部重命名属性(参数结构不变)

如果你的需求只是想在函数里把currentPrice改个名字使用,不需要改变外部传入参数的属性名,修正解构写法即可——把Percentage: percent改成currentPrice: percent,这样就完全符合Prices的类型要求:

const CalculatePercentage = ({ currentPrice: percent, totalPrice: total }: Prices): number => {
  // 函数内直接用percent代替currentPrice做逻辑处理
  return (percent / total) * 100;
};

方案2:创建属性名重命名后的新类型

如果确实需要外部传入的参数属性名是Percentage(而非currentPrice),同时又想复用Prices的类型定义,可以基于原接口创建新的类型别名:

// 基于Prices生成新类型,将currentPrice替换为Percentage,保留totalPrice的类型
type PricesWithPercentage = {
  Percentage: Prices['currentPrice'];
  totalPrice: Prices['totalPrice'];
};

// 函数参数使用这个新类型
const CalculatePercentage = ({ Percentage: percent, totalPrice: total }: PricesWithPercentage): number => {
  return (percent / total) * 100;
};

也可以用更简洁的工具类型组合写法,效果完全一致:

type PricesWithPercentage = Omit<Prices, 'currentPrice'> & { Percentage: Prices['currentPrice'] };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:55:34