Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an async function to a type def file?

Tags:

typescript

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?

like image 896
dewijones92 Avatar asked Jan 25 '18 16:01

dewijones92


People also ask

How do I add async function?

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!

How do you declare async method in interface TypeScript?

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.

Does an async function need to be called?

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.


1 Answers

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.

like image 199
Aaron Beall Avatar answered Oct 22 '22 16:10

Aaron Beall