I’m trying to infer the type of a class property based on a method’s conditional type returning from another class.
The Parent class property is assigned within the Builder class method, it has to be like that.
The code has to be like this.
The real scenario is much more complicated with decorators and more dependencies, but at the end it works like this:
class ClassA {
propString: string
}
class ClassB {
propNumber: number
}
type TypeAConstructor = new () => ClassA
type TypeBConstructor = new () => ClassB
class Builder {
body: ClassA | ClassB
build<T extends TypeAConstructor | TypeBConstructor>(Ctr: T, parent: Parent): T extends TypeAConstructor ? ClassA : ClassB {
// I have to instantiate in this way, the real scenario is much more complex, but at the end it works like this
if (new Ctr() instanceof ClassA) {
this.body = new ClassA()
} else {
this.body = new ClassB()
}
// Parent obj will be assigned from this method
parent.obj = this.body
// Return type is correct
return this.body as any // If I don't set as any, typescript throws an error
}
}
class Parent {
obj: ClassA | ClassB // ** Type should be inferred here. How to do it? **
builder: Builder = new Builder()
constructor() {
const body = this.builder.build(ClassA, this)
// body type is correct, it is ClassA
// this.obj has no type, and it should be ClassA
}
}