Categories
TypeScript Answers

How to create an async constructor functions in TypeScript?

Spread the love

Sometimes, we want to create an async constructor functions in TypeScript.

In this article, we’ll look at how to create an async constructor functions in TypeScript.

How to create an async constructor functions in TypeScript?

To create an async constructor functions in TypeScript, we can create a factory method.

For instance, we write

class MyClass {
  private mMember: Something;

  private constructor() {}

  public static CreateAsync = async () => {
    const me = new MyClass();
    me.mMember = await SomeFunctionAsync();
    return me;
  };
}

to create the MyClass class that has a private constructor.

We use it to create a MyClass instance inside the CreateAsync function.

The function is static so we don’t need to instantiate MyClass to call it.

We return me which is the resolve value of the promise returned by CreateAsync.

Then we can use it by writing

const m = await MyClass.CreateAsync();

in an async function.

Conclusion

To create an async constructor functions in TypeScript, we can create a factory method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *