← 返回完整题库
Typescript中等

说一说TypeScript中的类及其特性。

参考答案

类是什么

类(class)是 TS 中构造对象、封装状态与行为的模板,语法基于 ES6 class,并额外支持类型标注、访问修饰符、抽象类、泛型、装饰器、参数属性等。

示例

class User {
  static count = 0;
  readonly id: number;
  private _name: string;
  protected age?: number;

  constructor(id: number, name: string, public email: string) {
    this.id = id;
    this._name = name;
    User.count++;
  }

  get name(): string { return this._name; }
  set name(v: string) { this._name = v.trim(); }

  greet(): string { return `hi ${this._name}`; }
}

TS 给类加的特性

  1. 成员类型标注:属性、方法参数、返回值。
  2. 访问修饰符:public(默认)/protected/private,另有 readonly、static、abstract。
  3. 参数属性:构造器参数前加修饰符自动声明并赋值。
  4. 严格初始化检查(strictPropertyInitialization):非可选属性必须在声明或构造器中初始化,否则报错;可用 ! 确定赋值断言或 declare。
  5. 抽象类:abstract class 与 abstract 方法,子类必须实现。
  6. **implements**:类实现接口,只做类型检查。
  7. 泛型类:class Box<T> {}。
  8. 装饰器:类/方法/属性/参数装饰器(需 experimentalDecorators)。
  9. **# 私有字段**:运行时真正私有。
  10. **this 类型**与 this 参数,用于链式调用。

与 ES5 构造函数的关系

TS 类编译到 ES5 时就是"构造函数 + 原型方法",extends 变成原型链 + 静态属性拷贝;编译到 ES2015+ 时直接输出 class。行为差异主要在"能否被 new、this 时机、静态继承"。

注意

  • private 只是编译期约束,运行时可通过下标访问绕过;要运行时私有用 #。
  • 类字段初始化顺序:父类字段 → 父类构造器 → 子类字段 → 子类构造器。
  • 在 constructor 里 super() 之前不能访问 this。

本题来自 计算机知识面试题库,共 921 道题。