2

I have an Interface and a Class which implements the methods, I didn't find a answer to my Problem by now. I have a function defined myAsyncFunction() in the Interface and i want to make it async:

export interface State {
  state: Class;

  myAsyncFunction(): any;
}
0

3 Answers 3

3

To the caller, an async function is just a function that returns a promise:

export interface State {
  state: string;
  myAsyncFunction(): Promise<any>;
}

const state : State = {
  state: 'foo',
  myAsyncFunction: async () => 'bar'
};
Sign up to request clarification or add additional context in comments.

Comments

1

TypeScript doesn't care if a function uses the async keyword. It only cares that it is a function, what arguments it takes, and what the return value is.

The only significance of the async keyword in that context is that the function will return a promise … which will be matched by any.

2 Comments

While this works, it does have the disadvantage that you can return something other than a promise, and you can't be more specific about what you really return. So if you type it to return string instead, it won't work.
@gustafc — That's general advice about any and not specific to this case.
0

Function is async when returns a Promise. Here is example how to define async function in interface:

interface Foo {
    bar: () => Promise<void>
}

Instead of void you can use any return type you want and of course you can use any parameters you want, for example:

interface Foo {
    bar: (test: string) => Promise<boolean>
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.