You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中Student类为何兼容Person接口?新手技术问询

为什么Student类能兼容Person接口?

嘿,这个问题问得特别好——刚上手TypeScript的面向对象特性时,这个构造器参数的小细节确实很容易被忽略!

你之所以会觉得Student没有lastName属性,是因为没注意到构造函数参数前的public修饰符的特殊作用:

在TypeScript里,当你给构造函数的参数加上public(或者private/protected)修饰符时,它会自动帮你完成两个操作:

  • 为类定义一个同名的实例属性
  • 在构造函数内部把传入的参数值赋值给这个属性

看你的Student类构造器:

constructor(public firstName: string, public middleInitial: string, public lastName: string) {
  this.fullName = firstName + " " + middleInitial + " " + lastName;
}

这三个带public的参数,相当于TypeScript帮你悄悄补了这些代码:

class Student {
  fullName: string;
  // 自动添加的实例属性
  public firstName: string;
  public middleInitial: string;
  public lastName: string;

  constructor(firstName: string, middleInitial: string, lastName: string) {
    // 自动赋值
    this.firstName = firstName;
    this.middleInitial = middleInitial;
    this.lastName = lastName;
    this.fullName = firstName + " " + middleInitial + " " + lastName;
  }
}

另外,TypeScript用的是结构类型系统——只要一个对象的结构(拥有的属性及对应类型)符合接口的要求,就会被认为兼容这个接口,不需要显式写implements Person。Person接口只要求有firstName和lastName两个字符串属性,而Student的实例刚好满足这一点,所以greeter(user)完全能正常运行。

如果把构造器参数的public去掉,那Student类确实不会自动生成这些属性,这时候调用greeter就会触发TypeScript的类型错误啦!

内容的提问来源于stack exchange,提问作者Nayeemul Islam Swad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:01:33