如何判断联合类型中的函数是TabWithSetIndex还是TabWithoutSetIndex?
如何区分TabWithSetIndex和TabWithoutSetIndex类型
由于TypeScript的类型信息在运行时会被擦除,没法直接通过类型本身判断,得借助运行时可识别的特征来区分,下面是两种可行的方法:
方法1:利用函数的length属性判断
函数的length属性返回它的形参个数,正好可以用来区分这两种组件:
TabWithoutSetIndex是无参数函数,length为0TabWithSetIndex是单参数函数,length为1
你可以写一个类型守卫函数让TypeScript自动推断类型:
function isTabWithSetIndex( tab: TabWithSetIndex | TabWithoutSetIndex ): tab is TabWithSetIndex { return tab.length === 1; } // 使用示例 const targetTab = tabs[0].tabContent; if (isTabWithSetIndex(targetTab)) { // 这里TypeScript会自动识别targetTab为TabWithSetIndex targetTab({ /* 传入TabContentProps结构的参数 */ }); } else { // 自动识别为TabWithoutSetIndex targetTab(); }
如果不想写类型守卫,也可以直接判断后手动断言类型:
const targetTab = tabs[0].tabContent; if (targetTab.length === 1) { (targetTab as TabWithSetIndex)({ /* 参数 */ }); } else { (targetTab as TabWithoutSetIndex)(); }
方法2:给函数添加自定义标识属性
如果担心函数length属性可能因为剩余参数、默认参数等场景出现误差,可以给组件函数加个自定义标识属性:
首先修改类型定义,给两种类型加上可选的标识字段:
type TabWithSetIndex = ((props: TabContentProps) => React.ReactElement) & { isWithSetIndex?: true; }; type TabWithoutSetIndex = (() => React.ReactElement) & { isWithSetIndex?: false; };
然后在定义组件时手动设置标识:
const MyTabWithIndex: TabWithSetIndex = (props) => <div>索引:{props.index}</div>; MyTabWithIndex.isWithSetIndex = true; const MyTabWithoutIndex: TabWithoutSetIndex = () => <div>无索引标签</div>; MyTabWithoutIndex.isWithSetIndex = false;
最后用类型守卫判断:
function isTabWithSetIndex( tab: TabWithSetIndex | TabWithoutSetIndex ): tab is TabWithSetIndex { return tab.isWithSetIndex === true; } // 使用示例 const targetTab = tabs[0].tabContent; if (isTabWithSetIndex(targetTab)) { targetTab({ index: 0 }); } else { targetTab(); }
内容的提问来源于stack exchange,提问作者Dima Kambalin
相关产品推荐
相关产品推荐

