如何根据值类型标记React组件的多个属性为废弃状态
React组件废弃属性类型的精准高亮方案
当前通过函数重载拆分新旧属性类型的方式,会导致混用不同类型属性时TS无法匹配任何重载签名,触发类型错误。要实现仅废弃类型属性高亮提示、同时支持混用新旧属性的需求,可以通过「联合类型+属性级废弃注释」的方式实现:
类型定义方案
import React from 'react'; type DeprecatedSpacingType = string; type NewSpacingType = number; interface InternalProps { children?: React.ReactNode; } // 为每个间距属性定义「新类型 + 带废弃标记的旧类型」的联合类型 type SpacingProps = { top?: NewSpacingType | /** @deprecated 请使用number类型的间距值 */ DeprecatedSpacingType; bottom?: NewSpacingType | /** @deprecated 请使用number类型的间距值 */ DeprecatedSpacingType; }; // 合并所有属性类型 type ContainerProps = InternalProps & SpacingProps & { ref?: React.Ref<HTMLDivElement>; }; // 组件实现(内部兼容新旧类型) const Container: React.FC<ContainerProps> = ({ children, top, bottom, ref }) => { // 运行时处理类型兼容,可根据实际需求调整 const resolvedTop = typeof top === 'string' ? parseInt(top, 10) || 0 : top; const resolvedBottom = typeof bottom === 'string' ? parseInt(bottom, 10) || 0 : bottom; return ( <div ref={ref} style={{ marginTop: resolvedTop, marginBottom: resolvedBottom }} > {children} </div> ); };
效果验证
// 全废弃用法:top、bottom均触发废弃警告 <Container top='aaa' bottom='bbb' /> // 全新用法:无任何警告 <Container top={111} bottom={222} /> // 混用用法:仅string类型的top触发警告,number类型的bottom正常 <Container top='aaa' bottom={222} />
批量处理优化
如果有大量属性需要添加废弃类型,可以封装工具类型减少重复代码:
// 工具类型:为指定属性添加废弃类型分支 type AddDeprecated<T, K extends keyof T, DeprecatedType> = Omit<T, K> & { [P in K]: T[P] | /** @deprecated 请使用新类型替代 */ DeprecatedType; }; // 使用工具类型生成最终Props type ContainerProps = AddDeprecated< InternalProps & { top?: NewSpacingType; bottom?: NewSpacingType }, 'top' | 'bottom', DeprecatedSpacingType > & { ref?: React.Ref<HTMLDivElement> };
内容的提问来源于stack exchange,提问作者Aleksandr
相关产品推荐
相关产品推荐

