Typescript 类型脚本继承扩展属性

Typescript 类型脚本继承扩展属性,typescript,object,inheritance,properties,Typescript,Object,Inheritance,Properties,我有两个简单的继承对象,用户和参与者 用户被定义为 export type userDoc = { firstname: string lastname: string email: string } export class User { props: userDoc = { firstname: "", lastname: "", email: "", {...} } } 和参与者(从用户继承)作为 现在我希望实现的

我有两个简单的继承对象,用户和参与者

用户被定义为


export type userDoc = {
  firstname: string
  lastname: string
  email: string
}

export class User {
  props: userDoc = {
      firstname: "",
      lastname: "",
      email: "", 
      {...}
  }
}
和参与者(从用户继承)作为

现在我希望实现的是在子类中扩展父类的属性。我之所以使用道具,是因为mongodb,而且这样分配道具比Object.assign()更安全

typescript引发以下错误:

TS2416: Property 'props' in type 'Participant' is not assignable to thesame property in base type 'User'.
  Type 'participantDoc' is missing the following properties from type 'userDoc': firstname, lastname, email, and 6 more.

你必须像在课堂上那样扩展道具的类型

改变

export type participantDoc = {
    pseudonym: string
    karma: number
    impact: number
    level: number
    experience: number
}

此外,如果您愿意将类型声明为接口,可以执行以下操作:

导出接口userDoc{
名字:string
姓氏:string
电子邮件:string
}
导出接口participantDoc扩展userDoc{
笔名:string
业力:数字
影响:数量
级别:数字
经验:数字
}

如果
用户
指定其
道具
字段的类型为泛型,则继承可以在
用户
参与者
类之间工作

另一个技巧是依赖常量(为空时的props值)来获取类型。它使代码更加简洁

const emptyUserProps={
名字:“,
姓氏:“,
电邮:“,
};
导出类型UserProps=typeof emptyUserProps;
导出类用户{
props=emptyUserProps as TProps;//此处需要类型断言'as TProps',以便使用'emptyUserProps'(属于'UserProps'类型,而不是'TProps')初始化字段
}
// -------
const emptyParticipantProps={
笔名:“,
业力:0,
影响:0,
级别:0,
经验:0,
};
导出类型ParticipantProps=空类型ParticipantProps;
导出类参与者扩展用户{
道具={
…清空你的道具,
…清空参与者道具,
};
}
但是如果
User
Participant
只共享
props
字段中的一些数据,则在基本接口上使用多态性比在类继承上使用多态性更安全:

使用道具导出接口{
道具:TProps;
}
// ----
const emptyUserProps={
名字:“,
姓氏:“,
电邮:“,
};
导出类型UserProps=typeof emptyUserProps;
导出类用户实现WithProps{
道具=空道具;
}
// -------
const emptyParticipantProps={
笔名:“,
业力:0,
影响:0,
级别:0,
经验:0,
};
导出类型ParticipantProps=空类型ParticipantProps;
导出类参与者使用props实现{
道具={
…清空你的道具,
…清空参与者道具,
};
}
另一个选项是使用单个泛型类和几个静态工厂方法,一个用于创建“基本”用户,另一个用于参与者:

const emptyUserProps={
名字:“,
姓氏:“,
电邮:“,
};
const emptyParticipantProps={
笔名:“,
业力:0,
影响:0,
级别:0,
经验:0,
};
导出类用户{
//`TProps`推断为`typeof emptyUserProps`
静态createUser(props=emptyUserProps){
返回新用户(道具);
}
//推断为`(emptyUserProps类型)和`(emptyParticipantProps类型)的'TProps``
静态createParticipant(道具={
…清空你的道具,
…清空参与者道具,
}) {
返回新用户(道具);
}
私有构造函数(公共props:TProps){}
}
export type participantDoc = {
    pseudonym: string
    karma: number
    impact: number
    level: number
    experience: number
}
export type participantDoc = {
    pseudonym: string
    karma: number
    impact: number
    level: number
    experience: number
} & userDoc