Is there a way to make a property on a Class
optional without it being undefined?
In the following example, note that the Class
constructor takes a type of itself (this is intentional)
class Test {
foo: number;
bar: string;
baz?: string;
constructor(test: Test) {
this.foo = test.foo;
this.bar = test.bar
this.baz = test.baz || "Default";
}
}
const first = new Test({foo: 1, bar: "Bob"});
const str = "Some Default String about Bob";
str.replace(first.baz, "New Value");
// Type 'undefined' is not assignable to type 'string | RegExp'.(
I am aware that I can use the !
operator, but would rather avoid it
str.replace(first.baz!, "New Value");
This question seems to address the issue —"class properties can't rely on default values"