首页 > 解决方案 > 扩展类型的原型

问题描述

我正在使用 Vue3 和 Typescript。基本上,我想要实现的是:

export type PersonId = string;

export interface Person {
    id: PersonId,
    lastSeen: Date
}

export type PersonOrId = Person | PersonId;

PersonOrId.prototype.collapse = function (): PersonId {
    let id: PersonId;
    if (this.hasOwnProperty('id'))
        id = (this as Person).id;
    else
        id = this as PersonId;

    return id;
}

然后稍后在代码中使用该函数来保持代码更清洁:

let result: PersonOrId = ...

let id = result.collapse()

但事实证明,你不能prototype一个type. 我可以使用 解决这个问题interface吗?如果是这样,怎么做?

标签: typescripttyping

解决方案


推荐阅读