Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to associate and infer property types in typescript from given value

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'.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In addition, a playground

>Solution :

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;
    }
}

Playground


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;
    }
}

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading