How can TypeScript understand whether this.a
will be set or if this.b
and this.c
will be set?
In the given code, it is ensured that there will never be a situation where all items are set or none are set due to how the constructor is structured.
export class MyClass {
readonly a?: SomeClass
readonly b?: string
readonly c?: string
constructor(a: SomeClass)
constructor(b: string, c: string)
constructor(...args: ([SomeClass] | [string, string])) {
if(args.length === 1) {
this.a = args[0]
} else {
this.b = args[0]
this.c = args[1]
}
}
echo() {
if (this.a instanceof SomeClass) {
} else {
someFunction(this.b, this.c)
}
}
}
someFunction
is showing an error:
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
I am aware of using
else if(typeof this.b === 'string' && typeof this.c === 'string')
, but I'm looking for a more concise approach. Is there another way to solve this?