在开发React并使用typescript编写代码的时候,我们经常会一个变量可能有多种类型,我们需要对其中的某些类型做特殊的处理的情况: 比如以下的代码:
interface RowProps {
// 对key是变量的处理:
[index: string]: string | number | CustomProps;
}
interface CustomProps {
custom: true;
render: React.ReactElement;
}
// 写一个类型判断的方法判断是不是custom的interface,注意is的用法:
const isCustom = (c: string | number | CustomProps): c is CustomProps => {
return !!(c as CustomProps).render;
};
/* dataList来自外部赋值,
要判断某个RowProps类型的变量到底是string还是number还是CustomProps,然后分别做不同的处理
*/
const dataList: RowProps[];
const keys = dataList.length > 0 ? Object.keys(totalList[0]) : []
const list = dataList.map((item, index) => (
<div
className={`f_r_l data_item ${index === dataList.length - 1 ? 'last_child' : ''}`}
key={index}
>
{keys.map((e, i) => {
if (isCustom(item[e])) {
// 注意as的用法:这里直接写 return item[e].render ts会报错
return (item[e] as CustomProps).render;
} else {
return <div style={{ width: width[i] }}>{item[e]}</div>;
}
})}
</div>
))