尝试将接口返回对象赋值给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
相关产品推荐
相关产品推荐

