You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:15:31