If we do not want to initialize members inside a constructor, we use this.
class OKGreeter {
// Not initialized, but no error
name!: string;
}
The idea of index signatures is to type objects of unknown structure when you only know the key and value types. The key of the index signature can only be a string
, number
, or symbol
For more information: https://dmitripavlutin.com/typescript-index-signatures/-
The order of class initialization, as defined by JavaScript, is:
Returned object of super() will replace ‘this’ of MsgError. As a result, this.sayHello() will not work.
The solution is to use Object.setPrototypeOf(this, MsgError.prototype) inside constructor after the super() call.
class MsgError extends Error {
constructor(m: string) {
super(m);
}
sayHello() {
return "hello " + this.message;
}
}
class MySafe {
private secretKey = 12345;
}
const s = new MySafe();
// Not allowed during type checking
console.log(s.secretKey);
//Property 'secretKey' is private and only accessible within class 'MySafe'.
// OK
console.log(s["secretKey"]);