如何获取map函数返回值的类型?React项目接入TypeScript相关问题
字段类型判断与TypeScript适配方案
一、运行时类型判断方法
你可以直接通过原生JS方法在运行时确认字段类型,覆盖绝大多数场景:
- 基础类型判断用
typeof运算符,注意规避两个常见坑:typeof null返回object、typeof 数组也返回object,需要单独判断:
// 打印每个name字段的精准类型 stateToProps?.forEach(item => { let type = typeof item.name if (item.name === null) type = 'null' if (Array.isArray(item.name)) type = 'array' // 如需判断Date、正则等特殊引用类型,可以用下面的方法 // type = Object.prototype.toString.call(item.name).slice(8, -1).toLowerCase() console.log(`name值:${item.name},类型:${type}`) })
二、添加TypeScript类型支持的实现方案
1. 先定义基础类型
根据运行时判断出来的字段类型,先定义对应的数据结构:
// 数组项的类型,可根据实际判断结果缩小联合类型的范围 interface ArticleItem { identifier: string; name: string | number | boolean; } // Redux根state的类型,可拆分到全局类型文件复用 interface RootState { articles: { sites: ArticleItem[]; }; siteArticles: { brokers: ArticleItem[]; }; }
2. 改造useSelector代码添加类型标注
// 给state加类型标注,同时指定返回值类型为ArticleItem[] const stateToProps = useSelector((state: RootState): ArticleItem[] => { const articles = { sites: state.articles.sites, brokers: state.siteArticles.brokers, }; // 给props.action加类型断言避免索引签名报错 return articles[props.action as keyof typeof articles]; });
3. 类型守卫收窄类型(可选)
如果需要在代码中根据不同的name类型走不同逻辑,可以写类型守卫函数让TS自动推导类型:
// 示例:判断name为string类型的守卫 function isStringName(item: ArticleItem): item is ArticleItem & { name: string } { return typeof item.name === 'string' } // 使用时可获得完整类型提示 stateToProps?.forEach(item => { if (isStringName(item)) { // 此处TS会自动识别item.name为string类型,支持调用所有字符串方法 console.log(item.name.toUpperCase()) } })
内容的提问来源于stack exchange,提问作者user10727653
相关产品推荐
相关产品推荐

