蓝色天空网mbsky.com · 知识 · 实践 · 创造TypeScript · 本地阅读预览
教程 / 前端开发 / TypeScript

TypeScript 访问修饰符

按类内、派生类和调用方理解public/protected/private,并分清readonly、参数属性和#私有字段。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

三种成员可见范围

修饰符类内部派生类代码类外调用方
public可访问可访问可访问
protected可访问可访问,另有受保护接收者兼容规则不能直接访问
private声明它的类内部可访问不能直接访问基类私有实现不能直接访问

不写访问修饰符的类成员默认public。它们约束TypeScript的访问和类型兼容,不是服务器权限系统;private/protected在生成的普通JavaScript属性上并不提供等价的运行时保密。

用公开方法校验修改

typescript · 阅读源码
class DemoAccount {
  private balance: number;
  constructor(initial: number) { this.balance = initial; }
  deposit(amount: number): void {
    if (!Number.isFinite(amount) || amount <= 0) throw new RangeError("数额无效");
    this.balance += amount;
  }
  getBalance(): number { return this.balance; }
}

默认不公开balance,deposit负责有效条件,getBalance提供观察。这里用普通数值演示封装,不引入真实账户或声称解决金融精度;实际业务应明确金额单位与整数/十进制契约。

子类可使用的状态与构造权限

typescript · 阅读源码
class Person { constructor(protected name: string) {} }
class Employee extends Person {
  constructor(name: string, private department: string) { super(name); }
  introduce(): string { return `${this.name}@${this.department}`; }
}

protected让派生实现使用name,但不把它暴露给外部调用。protected构造函数可限制外部new而允许派生;private构造函数可配合类内静态工厂控制构造。类型限制仍不代替运行时授权。

只读与可见性是两个维度

typescript · 阅读源码
class User {
  constructor(public readonly id: number, private readonly originalName: string) {}
  label(): string { return this.originalName; }
}

readonly通常只能在字段初始化或所属类构造流程中赋值;与private/public/protected可以组合。它不是访问修饰符中的第四种范围,也不会递归冻结对象引用的内容。

参数属性与真正私有字段

typescript · 阅读源码
class Point {
  constructor(public x: number, public y: number, private z: number) {}
  sum(): number { return this.x + this.y + this.z; }
}
class Counter {
  #value = 0;
  next(): number { return ++this.#value; }
}

构造参数带public/private/protected/readonly时可同时声明并初始化成员。这个TypeScript语法需要相应编译支持;仅能擦除类型的执行器不一定支持它。JavaScript的#value有运行时私有语义,与TypeScript private不同,相关语法和目标环境仍须匹配。

完整核心源码与验证目标

typescript · 阅读源码
export {};
class DemoAccount {
 private balance:number;
 constructor(initial:number){this.balance=initial;}
 deposit(amount:number):void{if(!Number.isFinite(amount)||amount<=0)throw new RangeError("数额无效");this.balance+=amount;}
 getBalance():number{return this.balance;}
}
class Person {constructor(protected name:string){}}
class Employee extends Person {
 constructor(name:string,private department:string){super(name);}
 introduce():string{return `${this.name}@${this.department}`;}
}
class Point {constructor(public x:number,public y:number,private z:number){}sum():number{return this.x+this.y+this.z;}}
class User {constructor(public readonly id:number,private readonly label:string){}getName():string{return this.label;}}
const account=new DemoAccount(1000);account.deposit(500);
const point=new Point(1,2,3);const user=new User(1,"蓝色天空网");
console.log(account.getBalance());
console.log(new Employee("学习者","技术部").introduce());
console.log(point.x,point.y,point.sum());
console.log(user.id,user.getName());
// account.balance; point.z; user.id=2; // 分别启用,观察私有/只读诊断
TypeScript 访问修饰符:蓝色天空网核心实验

所需环境:固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行

当前源码 SHA256:8bc817c6fa66cb19b7fc5fbce416c209f29f05907954f148ba02d017402a6a35

下载本站示例源码
预期结果 · 待实际运行核验
  • 1500
  • 学习者@技术部
  • 1 2 6
  • 1 蓝色天空网;取消注释的非法访问应单独验证编译诊断

常见错误与边界

  • 把private当运行时秘密
  • 将readonly当深冻结
  • 以any绕过访问限制后仍说已保护
  • 仅擦除类型的执行器直接运行参数属性

练习与解答

怎样让基类不能从外部new,但允许Employee继承?

展开参考解答

把基类构造函数设为protected;普通外部new被类型检查拒绝,派生类仍可super。运行时权限另行设计。

规范与官方依据