我试图使用条件类型,但是它没有按预期工作。 我期望abc的类型为数字,但它返回一个字符串。 对此的任何帮助将不胜感激。
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 :(得分:2)
您应该向EntityBase添加一些非可选属性,例如
class EntityBase {
public isEntityBase = undefined
...
}
这是因为TypeScript使用结构子类型,换句话说,它通过查看对象的结构(属性名称)来检查对象是否实现了某些接口。
为了不污染EntityBase的API,可以使用Symbols:
const isEntityBase = Symbol()
class EntityBase {
public [isEntityBase] = undefined
}