我正在使用 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
解决这个问题吗?如果是这样,如何?