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.