I have the following example code that resembles the actual classes (I do not put the full class because is quite big.
type accepted = 'a' | 'b';
type objects = A | B;
class A {
aprop: string[] = [];
add(): void {}
}
class B {
myprop: string = '';
anotherprop: number = 1;
add(): void {}
}
class C<T extends objects> {
prop1: accepted;
prop2: T;
constructor (prop1: accepted, prop2: T) {
this.prop1 = prop1;
this.prop2 = prop2;
}
}
const right1 = new C('a', new A());
const right2 = new C('b', new B());
const wrong1 = new C('a', new B()); //should not be possible
What I want is to make sure that whenever I instantiate a class C with certain value of prop1
(a set of possible strings) the prop2
shall be its correspondent class.
In other words, I want to infer that prop2
is class A or B when the value of prop1
is 'a'
or 'b'
.
In addition, a playground
CodePudding user response:
Since you only have two classes in this example, I think you should use the overloads example.
class C<T extends objects> {
prop1: accepted;
prop2: T;
constructor(prop1: 'a', prop2: A);
constructor(prop1: 'b', prop2: B);
constructor (prop1: accepted, prop2: T) {
this.prop1 = prop1;
this.prop2 = prop2;
}
}
If you have more classes, you can use a map like this:
type ClassMap = {
a: A;
b: B;
}
class C<T extends accepted> {
prop1: T;
prop2: ClassMap[T];
constructor (prop1: T, prop2: ClassMap[T]) {
this.prop1 = prop1;
this.prop2 = prop2;
}
}