Is there any way that you can have a property on a Class that is optional, but won't be undefined?
Note in the example below, the Class constructor takes a type of itself (that's 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 know I can use the ! operator, but would prefer not to
str.replace(first.baz!, "New Value");
Seems maybe this question addresses it the answer — "class properties can't rely on default values"
As far as I can tell, you don't want the class property to be optional you want the constructor parameter to be optional. Which is easy enough to do:
interface TestParams {
foo: number;
bar: string;
baz?: string; // optional
}
class Test {
foo: number;
bar: string;
baz: string; // NOTE: not optional!
constructor ({
foo,
bar,
baz,
}: TestParams) {
this.foo = foo;
this.bar = bar;
this.baz = baz ?? "Default";
}
}
Note that I used the nullish coalescing operator rather than logical "or" so that if baz is undefined we'll assign the default but if it's an empty sting it won't be overwritten. If you are really concerned about the duplication, and you don't mind having your constructor take positional parameters rather than an object you can condense it back down quite a bit:
class Test2 {
constructor (
public foo: number,
public bar: string,
public baz = "Default",
) {}
}
The behavior isn't quite the same regarding the optional param, but it's pretty close.