📝 基本语法
class Circle {
private _radius: number = 0;
// getter:读取属性
get radius(): number {
return this._radius;
}
// setter:设置属性
set radius(value: number) {
if (value < 0) {
throw new Error('Radius cannot be negative');
}
this._radius = value;
}
// 只读计算属性(只有 getter)
get area(): number {
return Math.PI * this._radius ** 2;
}
get diameter(): number {
return this._radius * 2;
}
}
const circle = new Circle();
circle.radius = 10; // 调用 setter
console.log(circle.radius); // 10,调用 getter
console.log(circle.area); // 314.16...
console.log(circle.diameter); // 20
// circle.area = 100; // Error: 只读属性
💡
存取器优势
使用 getter/setter 可以在访问或修改属性时添加验证逻辑,实现数据封装和保护。
💻 实际应用
class User {
private _email: string = '';
private _password: string = '';
// 邮箱验证
get email(): string {
return this._email;
}
set email(value: string) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(value)) {
throw new Error('Invalid email format');
}
this._email = value;
}
// 密码验证
get password(): string {
return this._password;
}
set password(value: string) {
if (value.length < 8) {
throw new Error('Password must be at least 8 characters');
}
this._password = value;
}
// 只读属性
get displayName(): string {
return this._email.split('@')[0];
}
}
const user = new User();
user.email = 'alice@example.com'; // OK
user.password = 'password123'; // OK
console.log(user.displayName); // alice
// user.email = 'invalid-email'; // Error: Invalid email format