Skip to content

Instantly share code, notes, and snippets.

@disco0
Last active October 27, 2020 05:16
Show Gist options
  • Save disco0/cd6e528189c06179c0f1ecf319cef6f0 to your computer and use it in GitHub Desktop.
Save disco0/cd6e528189c06179c0f1ecf319cef6f0 to your computer and use it in GitHub Desktop.
TypeScript - Async Constructor Workaround Example
/**
* Original code from [comment in microsoft/TypeScript issue #13355](https://github.com/microsoft/TypeScript/issues/13355#issuecomment-313847099)
*/
function loooooongTask() {
return new Promise<string>(resolve => {
setTimeout(() => {
resolve("world");
}, 3000);
})
}
class Foo {
name: string;
constructor() { // I want add type assertion to here. Promise<Foo>.
return loooooongTask().then(v => {
this.name = v;
return this;
})
}
hello() {
console.log(`Hello, ${this.name}`);
}
}
(async () => {
const obj = await new Foo();
obj.hello();
})();
/**
* Modified form
*/
class ModFoo
{
name!: string;
static new(): Promise<ModFoo>
{
return (async (instance: ModFoo) =>
{
instance.name = await loooooongTask();
return instance;
})(new ModFoo())
}
private constructor() { }
hello() {
console.log(`Hello, ${this.name}`);
}
}
(async () => {
const obj = await ModFoo.new();
obj.hello();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment