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

尝试将接口返回对象赋值给window.location.href时遇类型错误求助

解决Type 'MyInterface'不可赋值给类型'string'错误

直接访问response对象的pulledCoolData属性即可——window.location.href需要字符串类型值,而你的response是包含该字符串属性的MyInterface实例:

getData(data.myData).then(response => {
    window.location.href = response.pulledCoolData; // 读取接口中的字符串属性
});

额外优化思路

如果getDataFromAPI返回的本身就是字符串,你可以调整getData函数的返回类型,直接返回字符串Promise,省去后续属性访问步骤:

const getData = async (passedData: string): Promise<string> => {
  const coolData = await getDataFromAPI(passedData);
  return coolData;
};

getData(data.myData).then(response => {
    window.location.href = response; // 此时response为字符串,符合类型要求
});

如果业务逻辑必须保留MyInterface类型的返回值,那么第一种直接访问属性的方式就是最适配的解决方案。

内容的提问来源于stack exchange,提问作者programmerGuy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 03:42:33