打字稿扩展。条件类型

Typescript extensions. Conditional Types

我试图使用条件类型,但它没有按预期工作。 我原以为 abc 的类型是数字,但它 returns 是一个字符串。 如有任何帮助,我们将不胜感激。

class TableIdClass {
    public tableId?: string;

    constructor(props: TableIdClass) {
        const { tableId } = props;
        this.tableId = `${Math.random()}`;

    }
}

export class TableBase extends TableIdClass {

    public createDate?: Date;

    constructor(props: TableBase) {
        super(props)
        const { createDate } = props;
        this.createDate = (createDate) ? createDate : new Date();
    }
}

export class EntityBase extends TableBase {
    public entityId?: string;
    public entityName?: string;
    public isActive?: boolean;

    constructor(props: EntityBase) {
        super(props)
        const { entityId, entityName, isActive } = props;
        this.entityId = entityId;
        this.entityName = (entityName) ? entityName : '';
        this.isActive = (typeof isActive === 'undefined') ? true : isActive;
    }
};

class SomeClass extends TableIdClass {

    constructor(prop: SomeClass) {
        super(prop)

    }
}

type abc = SomeClass extends EntityBase ? string : number; // Returns string.

您应该向 EntityBase 添加一些非可选的 属性 例如

class EntityBase {

    public isEntityBase = undefined
    ...
}

这是因为 TypeScript 使用结构子类型化,换句话说,它通过查看对象的结构(属性名称)来检查对象是否实现了某些接口。

为了不污染EntityBase的API,可以使用Symbols:

const isEntityBase = Symbol()

class EntityBase {

    public [isEntityBase] = undefined


}