TypeScript教程之四:类


由微软推出的TypeScript自从一推出就广受关注,现在无论开发前端React/Vue,还是后端API,很多项目中都广泛接受了TypeScript。下面介绍TS中类的使用。

TypeScript
TypeScript

类的定义

TypeScript
class Employee {
    name: string;
    salary: number;

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

    intro() {
        return "My name is: " + this.name + ", My salary is: " + this.salary;
    }
}

const paul = new Employee('Paul', 2000);
console.log(paul.intro());

类的继承

TypeScript
class Employee {
    name: string;
    salary: number;

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

    intro() {
        return "My name is: " + this.name + ", My salary is: " + this.salary;
    }
}

class Manager extends Employee {
    department: string;

    constructor(name: string, salary: number, dept: string) {
        super(name, salary);
        this.department = dept
    }

    intro() {
        return super.intro() + ", I manage " + this.department
    }
}

const paul = new Manager('Paul', 2000, 'Finance');
console.log(paul.intro());

在子类的构造函数中的第一行,必须通过super显式调用父类的构造函数

注意,**在定义intro函数的时候不要使用箭头函数,否则无法在子类中使用super.intro()**。

类成员访问修饰符

这点和Java一样,分为三种:

  • private: 只有类内部能访问
  • protected: 类内部以及子类中可以访问
  • public:在任何地方包括类外部可以直接访问

只读属性readonly

可以使用 readonly 关键字来指定一个只读的属性。通过这种方式,可以保护类的属性不会被意外赋值。

TypeScript
readonly name: string;

类定义的简写方式

TypeScript
class Employee {
    constructor(private name: string, private salary: number) {
    }
}

getter及setter

getter和setter的目的就是提供访问类私有成员的方法,同时可以添加额外的验证逻辑防止赋予非法值到类属性上。需要注意其语法的特殊之处,比如,不是getAge和setAge方法。

TypeScript
class Person {
    private _age: number;

    constructor(theAge: number) {
        this._age = theAge;
    }

    public get age() {
        return this._age;
    }

    public set age(theAge: number) {
        if (theAge <= 0 || theAge >= 200) {
            throw new Error('The age is invalid');
        }
        this._age = theAge;
    }
}

const lucy = new Person(12);
lucy.age = 18;
console.log(lucy.age);

文章作者: 逻思
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 逻思 !