简体   繁体   English

关于TypeScript Promise返回类型的困惑

[英]Confusions about TypeScript Promise return type

I have the following code in TypeScript React:我在 TypeScript React 中有以下代码:

const AirQuality= async ():Promise<string>=>{
    console.log('Air Quality')
    let data = await fetch(url,{
        method:'GET',
        // mode:'no-cors'
    })
    return data.json()
}

As you can see here, data.json() was returned from the function. The thing I don't get is why I am not getting an error when I define the Promise type as string.正如您在此处看到的, data.json()是从 function 返回的。我不明白的是,当我将 Promise 类型定义为字符串时,为什么没有出现错误。 What is the issue here?这里的问题是什么? I changed Promise type to number, still, no error is shown.我将 Promise 类型更改为数字,仍然没有显示错误。 What could be the cause for that?可能是什么原因造成的?

json() parses the returned JSON into a JavaScript object structure. json()将返回的JSON解析成JavaScript object结构。 Since this can be any kind of object depending on what the server returns, it has the type Promise<any> .由于这可以是任何类型的 object,具体取决于服务器返回的内容,因此它的类型为Promise<any>

An any type can be converted to anything including number or string, which is why you don't see an error. any类型都可以转换为任何类型,包括数字或字符串,这就是您看不到错误的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM