I am trying to add an async function definition to for async-busboy;
I have created a file "async-busboy.d.ts"
declare module 'async-busboy' {
export default async function asyncBusby
(subString: any): Promise<any>;
}
But this gives me the error: "error TS1040: 'async' modifier cannot be used in an ambient context."
How do I write async function defs?
Thanks
EDIT Thanks @Titian Cernicova-Dragomir and @Aaron for your answer. But when I call it I get an error
const dddd = await asyncBusboy(22);
[ts] 'await' expression is only allowed within an async function.
Any suggestions?
async function foo() { const p1 = new Promise((resolve) => setTimeout(() => resolve("1"), 1000)); const p2 = new Promise((_, reject) => setTimeout(() => reject("2"), 500)); const results = [await p1, await p2]; // Do not do this!
To type an async function in TypeScript, set its return type to Promise<type> . Functions marked async are guaranteed to return a Promise even if you don't explicitly return a value, so the Promise generic should be used when specifying the function's return type.
Async functions are not necessarily required to have an await call inside it, but the reason behind making a function async is that you need an asynchronous call for which you want to wait for the result before moving forward in the thread.
All you need is this:
declare module 'async-busboy' {
export default function asyncBusby
(subString: any): Promise<any>;
}
The fact that it returns a Promise
is what makes it of async type (nothing related to the async
modifier). Consumers are expected to await
the any
value now.
On the other hand, the async
modifier is used to augment the function (body) implementation (what it returns becomes wrapped in a promise). Since the type-def doesn't deal with the implementation, therefore the async
isn't allowed in the type-def.
In other words, from the perspective of the method/function interface the async
modifier is not saying/changing anything and therefore is not needed in the interface declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With