← 返回完整题库
Typescript简单

TypeScript支持的访问修饰符有哪些?

参考答案

三种(TS 4.x 起)

| 修饰符 | 可访问范围 | 说明 |
| --- | --- | --- |
| public | 任意位置 | 默认值,可省略 |
| protected | 类内部 + 子类内部 | 子类可访问,外部不可 |
| private | 仅当前类内部 | 子类也不能访问(TS 编译期检查) |
| readonly | 只读 | 不是访问修饰符,但常一起用 |

示例

class Person {
  public name: string;
  protected age: number;
  private secret = 'xxx';
  readonly id: number;

  constructor(name: string, age: number, id: number) {
    this.name = name;
    this.age = age;
    this.id = id;
  }
}

class Student extends Person {
  study() {
    this.age;     // ✅ protected 子类可见
    this.secret;  // ❌ private 子类不可见
  }
}
new Person('a', 1, 1).secret;  // ❌ 外部不可见

参数属性简写

class Person {
  constructor(
    public name: string,
    protected age: number,
    private secret?: string,
    readonly id = 0,
  ) {}
}

构造器参数前加修饰符会自动声明并赋值同名属性,省去重复代码。

进阶:# 私有字段(ECMAScript 私有)

class A { #x = 1; getX() { return this.#x; } }
  • private 只是编译期约定,运行时可通过 obj['secret'] 绕过,编译后属性名不变。
  • #x 是运行时真正私有,外部完全无法访问,且编译后会做降级处理。
  • 需要"运行时不可访问"用 #,只需要类型检查用 private。

其他相关

  • abstract:抽象类/抽象方法,不是访问修饰符,但常一起考。
  • static:静态成员,属于类本身。
  • declare 字段:只声明类型不生成初始化代码。
  • 接口不能用访问修饰符,只能用 readonly。

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