raw-body icon indicating copy to clipboard operation
raw-body copied to clipboard

How do I use this in TypeScript?

Open jameshfisher opened this issue 3 years ago • 3 comments

I'm confused by the example. It imports the entire module as getRawBody, but then calls it as a function. When I try to use it this way, I get a reasonable type error:

This expression is not callable.
  Type '{}' has no call signatures.ts(2349)
webhook.ts(1, 1): Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead.

However, I cannot use a default import either. This gives me the type error:

Module '"foo/node_modules/raw-body/index"' can only be default-imported using the 'allowSyntheticDefaultImports' flagts(1259)
index.d.ts(87, 1): This module is declared with using 'export =', and can only be used with a default import when using the 'allowSyntheticDefaultImports' flag.

jameshfisher avatar Apr 26 '22 18:04 jameshfisher

I think the problem is this line: https://github.com/stream-utils/raw-body/blob/6bfe9bc824829485702994ca56e8016bbba87de6/index.d.ts#L87

Should this not be export default getRawBody;?

jameshfisher avatar Apr 26 '22 19:04 jameshfisher

Hi @jameshfisher sorry for your trouble. I really don't know anything about TypeScript and rely on contributions for anything TypeScript related. The given definitions and example were contributed in PR #53 . I did test at the time to at least confirm it was working. Perhaps TypeScript has changed something? Any contributions around this would be welcome!

dougwilson avatar Apr 26 '22 19:04 dougwilson

I don't know much either, and the JS/TS/CommonJS/ES6 compatibility is a horror story ...

I see now that your implementation literally does module.exports = getRawBody. So to import this module from ES6, we need import * as getRawBody from 'raw-body'. So I think your ES6 example is correct, actually.

I think the issue is that I have allowSyntheticDefaultImports turned off. I'm reluctant to turn it on, basically because I don't really understand it ...

jameshfisher avatar Apr 26 '22 19:04 jameshfisher