TypeScript新手求助:如何读取回调函数的JSON响应?
TypeScript新手问题:如何从回调函数读取函数的响应
原问题场景
你写了一个获取HTML内容的getContent函数,代码如下:
async function getContent(src: string) { try { const response = await fetch(src); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = { content: await response.text(), correlationId: response.headers.get("x-correlationid") }; return result; } catch (error) { if (error instanceof Error) { return error.message; } else { return 'An unexpected error occurred'; } } }
尝试调用时用result.json()读取响应,却收到TypeScript报错:"Property json does not exists on type string",调用代码如下:
getContent(src) .then( result => result.json()) .then( post => { iframe.contentDocument.write(post.content); }) .catch( error => { console.log(error); });
问题根源
getContent函数的返回类型不一致:
- try块返回包含
content和correlationId的对象 - catch块返回字符串
TypeScript会推断该函数的返回类型为{ content: string; correlationId: string | null; } | string,所以调用时result可能是字符串,自然没有json()方法。另外,getContent内部已经通过response.text()把响应转成了文本,不需要再调用json()。
修正方案
让catch块返回和try块结构一致的对象,确保函数返回类型统一。更新后的函数:
async function getContent(src: string) { try { const response = await fetch(src); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = { content: await response.text(), correlationId: response.headers.get('x-correlationid') }; return result; } catch (error) { if (error instanceof Error) { return { content: error.message, correlationId: undefined }; } else { return { content: 'An unexpected error occurred', correlationId: undefined }; } } }
对应的正确调用方式:
getContent(src) .then( result => { iframe.contentDocument.write(result.content); console.log(`I have the correlation ${result.correlationId}`); }) .catch( error => { console.log(error.content); });
内容的提问来源于stack exchange,提问作者Cristobal BL
相关产品推荐
相关产品推荐

