Typescript oneOf Type类

时间:2019-03-02 17:45:30

标签: typescript inheritance multiple-inheritance typescript-typings

class CoreClass {
    coreProp: string
    // cannot do classABProp: string | number
    // as it interferes with persistence and cannot be easily 
    // used to define database schema. 
}

class ClassA extends CoreClass {
    classAProp: string

};

class ClassB extends CoreClass {
    classBPorp: number
};

class SubClass extends CoreClass {
    // Expected Props    
    // coreProp: string
    // classAProp: string || classBPorp: number
    // should have atleast one of the two.

}

所以我一直在寻找一种整齐的方法。 我不愿意重复定义本质上是在做同样事情的SubClass。

我确实为每个类都有一个构造函数,所以我真的不希望为实现相同目的而定义单独的类型。

似乎是一个小问题,但我无法解决。

在同一方面的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

您似乎在这里定义接口而不是类。怎么样:

interface CommonInterface {
  coreProp: string
}

interface InterfaceA extends CommonInterface {
    classAProp: string
};

interface InterfaceB extends CommonInterface {
    classBProp: number
};

type CoreInterface = InterfaceA | InterfaceB;

const testStringProp: CoreInterface = { coreProp: 'test', classAProp: "testString" };
const testNumberProp: CoreInterface = { coreProp: 'test', classBProp: 43 };

const testError: CoreInterface = { coreProp: 'test' }; 
//error: needs either classAProp or classBProp

通过实例化新对象来实现接口:

class CommonClass {
    coreProp: string
    // ...
}

class ClassA extends CommonClass {
    classAProp: string;

    constructor(props: InterfaceA) {
        super();
        this.coreProp = props.coreProp;
        this.classAProp = props.classAProp;
    }
};

class ClassB extends CommonClass {
    classBProp: number;

    constructor(props: InterfaceB) {
        super();
        this.coreProp = props.coreProp;
        this.classBProp = props.classBProp;
    }
};

class ClassAorB extends CommonClass {
    classAProp: string;
    classBProp: number;

    constructor(props: CoreInterface) {
        super();
        this.coreProp = props.coreProp;
        const propsA = props as InterfaceA;
        const propsB = props as InterfaceB;
        if (propsA.classAProp) {
            this.classAProp = propsA.classAProp
        }
        if (propsB.classBProp) {
            this.classBProp = propsB.classBProp
        }
    }
};


const objOfClassA = new ClassA({ coreProp: 'test', classAProp: 'testString' });
const objOfClassB = new ClassB({ coreProp: 'test', classBProp: 43 });
const objA = new ClassAorB({ coreProp: 'test', classAProp: 'testing' });
const objB = new ClassAorB({ coreProp: 'test', classBProp: 43 });

const testError = new ClassB({coreProp: 'test'}); 
//error: needs classBProp
const testAntotherErr = new ClassAorB({coreProp: 'test'}) 
//error: needs either classAProp or classBProp