1

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.
0

1 Answer 1

2

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


} 
Sign up to request clarification or add additional context in comments.

5 Comments

nope does not help. checked it in typescript playground
@NurbolAlpysbayev better yet, make it private (so no classes can mistakenly implement the interface), and don't assign a value to it, type it as undefined, no runtime cost :) private [isEntityBase]: undefined;
Thank you, @TitianCernicova-Dragomir. You are true about true :-). However it's public because otherwise IDE will complain "unused private bla bla".
btw we could make it private and ignore it seems to be a fair place to use ts-ignore.
@NurbolAlpysbayev forgot about unused privates :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.