TypeScript 的类有哪些成员可见性

文章类型:TypeScript

发布者:hp

发布时间:2025-03-14

一:引言

TypeScript 作为 JavaScript 的超集,通过‌静态类型检查‌‌和‌类型系统演进‌‌,显著提升了代码的可靠性与开发效率,那么,有那些成员可见呢?

二:类别

1:public‌(默认可见性):成员可在类内部、外部及子类中自由访问

class Person {
  public name: string; // 默认 public,可省略修饰符
  constructor(name: string) { this.name = name; }
}
const person = new Person("Alice");
console.log(person.name); // 直接访问外部属性 → "Alice" ‌

2:private‌:仅允许在定义该成员的类内部访问,子类和外部均不可访问

class Person {
  private id: string;
  constructor(id: string) { this.id = id; }
  public printId() { console.log(this.id); } // 类内部访问 private 成员
}
const person = new Person("123");
person.printId(); // 合法 → "123"
console.log(person.id); // 编译错误:属性私有 ‌

3:protected‌:允许在类内部及继承它的子类中访问,但外部不可访问

class Person {
  protected age: number;
  constructor(age: number) { this.age = age; }
}
class Employee extends Person {
  public getAge() { return this.age; } // 子类访问 protected 成员
}
const emp = new Employee(30);
console.log(emp.getAge()); // 合法 → 30
console.log(emp.age); // 编译错误:外部不可访问 ‌

三:补充

1:静态成员可见性‌:(static)

class MyClass {
  private static secret = "hidden";
  public static getSecret() { return MyClass.secret; } // 类内部访问私有静态成员
}
console.log(MyClass.getSecret()); // 合法 → "hidden"
console.log(MyClass.secret); // 编译错误 ‌:ml-citation{ref="5" data="citationList"}

2: 只读属性‌:(readonly)

class Person {
    public readonly name: string;
    constructor(name: string) {
        this.name = name;
    }
    
    setName(newName: string) {
        // 错误: 无法为只读属性赋值
        this.name = newName;
    }
}

let john = new Person("John");
// 错误: 无法为只读属性赋值
john.name = "Jack";

四:总结

  1. public:默认可见性。类的成员是 public 时,可以在类的外部和内部访问。
  2. private:类的成员是 private 时,只能在类的内部访问,不能在类的外部或继承的子类中访问。
  3. protected:类的成员是 protected 时,可以在类的内部和继承的子类中访问,但不能在类的外部访问