Typescript oneOf类的类型

问题描述 投票:0回答:1
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,这实际上是在做同样的事情。

我确实为每个类都有一个构造函数,所以我真的不想定义单独的类型来完成相同的操作。

看起来像一个微不足道的问题,但我无法理解它。

对此有任何帮助将受到高度赞赏。

typescript inheritance multiple-inheritance typescript-typings
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.