简体   繁体   中英

TypeScript and Node https.get()

I'm starting to convert a project to TypeScript and I'm encountering an error I'm not sure how to solve.

When I write:

https.get(`someUrl`, resp => {
  // Define Buffer
  let buffer = '';
  // Fill buffer
  resp.on('')
});

It gives me

[ts] Parameter 'resp' implicitly has an 'any' type. [7006]

I know I can 'fix' it by changing

https.get(`someUrl`, resp => {

to

https.get(`someUrl`, (resp: Object) => {

Is this the correct solution? Also, TS has no idea what resp actually contains. When I write normal JS it just shows me what methods and props there are but with TS I get nothing. When I get to resp.on('') it tells me that on does not exist on Object . Is this expected or am I doing something wrong? Do I need to write an interface for the https.get function?

I'm using Visual Studio Code

Is it because I'm using a module that is not intended to be used with TS? I think it could be simply that.

It base on the https.get callback function parameter type. Usually it need to be define either on the resp type or on the function type, so let say you create a type T, which you expect to get from the request

type ResponseType = { data: any };

then you can add to the function call like

https.get<ResponseType>(...);

or

https.get(`someUrl`, (resp: ResponseType) => {...}

Object type is quite flexible and it won't show if you use a property that is not existing in the response type. so I won't use that unless there're no other choices

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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