Typescript Tricks
Private Property Async Initialization
For the use cases where you run some async operation inside your class constructor and a private property in your class gets defined asynchronously, TypeScript throws an error, saying all class properties must be synchronously defined inside the constructor.
To override this behavior and tell TypeScript that you know you will assign that private property a value, you can use the !: definite assignment assertion operator.
class MyClass {
// say this will definitely be assigned a value
private myProp!: string;
constructor() {
this.init();
}
// set private property asynchronously
async init() {
this.myProp = await someAsyncOperation();
}
}
Extract type of array entry
The (typeof arrayName)[number] helps get the typeof an array entry.
const statuses = ["active", "inactive"] as const;
type Status = (typeof statuses)[number]; // "active" | "inactive"