调用Bloomberg API映射对象时出现Property 'title' does not exist on type 'never'错误
解决TypeScript中“Property 'title' does not exist on type 'never'”错误
这个错误的核心原因是TypeScript无法推断出data数组的具体类型,默认将其判定为never[]类型,导致访问item.title时触发类型检查报错。以下是具体解决步骤:
- 定义数据类型接口
先为Bloomberg API返回的单条数据定义明确的TypeScript接口,明确字段类型:
interface BloombergItem { title: string; longURL: string; // 可添加其他需要用到的字段 }
- 指定data变量的类型
在声明data状态时,直接指定其类型为上述接口的数组:
const [data, setData] = useState<BloombergItem[]>([]);
- 对齐API响应类型
在请求API并处理响应时,确保将返回数据转换成对应类型(根据实际API返回结构调整):
const fetchData = async () => { const res = await fetch('你的Bloomberg API请求地址'); const responseData = await res.json(); // 假设API返回的是符合BloombergItem结构的数组,用类型断言对齐 setData(responseData as BloombergItem[]); };
- 可选:添加类型守卫做校验
如果不确定API返回数据的结构是否稳定,可以添加类型守卫来过滤不符合要求的数据:
function isBloombergItem(item: unknown): item is BloombergItem { return typeof item === 'object' && item !== null && 'title' in item && 'longURL' in item; } // 在设置数据前过滤无效项 setData(responseData.filter(isBloombergItem));
内容的提问来源于stack exchange,提问作者Anurag
相关产品推荐
相关产品推荐

