Amol Gupta
Amol Gupta

Reputation: 2554

Typescript extensions. Conditional Types

I was trying to use conditional type but it does not work as expected. I was expecting type of abc would be number but it returns a string. Any help on the same would be appreciated.

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.

Upvotes: 1

Views: 81

Answers (1)

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21851

You should add to EntityBase some non-optional property e.g.

class EntityBase {

    public isEntityBase = undefined
    ...
}

This is because TypeScript uses structural subtyping, in other words it checks whether an object implements some interface, by looking at the object's structure (names of properties).

In order to not pollute the API of EntityBase, you could use Symbols:

const isEntityBase = Symbol()

class EntityBase {

    public [isEntityBase] = undefined


} 

Upvotes: 2

Related Questions