繁体   English   中英

如何从给定值关联和推断 typescript 中的属性类型

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

我有以下类似于实际类的示例代码(我没有放完整的 class 因为它很大。

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

我想要确保每当我实例化一个 class C 时, prop1的某个值(一组可能的字符串) prop2应该是其对应的 class。

换句话说,当prop1的值为'a''b'时,我想推断prop2是 class A 或 B。

此外, 游乐场

由于在此示例中只有两个类,我认为您应该使用重载示例

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

操场


如果你有更多的课程,你可以像这样使用 map:

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

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM