TypeScript 类

摘要:在本教程中,您将了解 TypeScript 类以及如何使用类创建对象。

TypeScript 类的介绍

JavaScript 没有像 Java 和 C# 等其他编程语言那样的类概念。在 ES5 中,您可以使用构造函数和原型继承来创建“类”。

例如,要创建一个具有三个属性 ssn、first name 和 last name 的Person类,您可以使用以下构造函数

function Person(ssn, firstName, lastName) {
    this.ssn = ssn;
    this.firstName = firstName;
    this.lastName = lastName;
}Code language: TypeScript (typescript)

接下来,您可以定义一个原型方法来通过连接 first name 和 last name 获取人的全名,如下所示

Person.prototype.getFullName = function () {
    return `${this.firstName} ${this.lastName}`;
}Code language: TypeScript (typescript)

然后,您可以通过创建一个新对象来使用 Person “类”

let person = new Person('171-28-0926','John','Doe');
console.log(person.getFullName());Code language: TypeScript (typescript)

它将在控制台中输出以下内容

John DoeCode language: TypeScript (typescript)

ES6 允许您定义一个类,它只是为创建构造函数和原型继承提供的语法糖。

class Person {
    ssn;
    firstName;
    lastName;

    constructor(ssn, firstName, lastName) {
        this.ssn = ssn;
        this.firstName = firstName;
        this.lastName = lastName;
    }
}Code language: TypeScript (typescript)

在类语法中,构造函数被清晰地定义并放置在类内部。以下代码将getFullName()方法添加到类中

class Person {
    ssn;
    firstName;
    lastName;

    constructor(ssn, firstName, lastName) {
        this.ssn = ssn;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    getFullName() {
        return `${this.firstName} ${this.lastName}`;
    }
}Code language: TypeScript (typescript)

使用Person类与使用Person构造函数相同

let person = new Person('171-28-0926','John','Doe');
console.log(person.getFullName());Code language: TypeScript (typescript)

TypeScript 类为类的属性和方法添加了类型注解。以下显示了 TypeScript 中的Person

class Person {
    ssn: string;
    firstName: string;
    lastName: string;

    constructor(ssn: string, firstName: string, lastName: string) {
        this.ssn = ssn;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    getFullName(): string {
        return `${this.firstName} ${this.lastName}`;
    }
}Code language: TypeScript (typescript)

当您为属性、构造函数和方法添加类型注解时,TypeScript 编译器将执行相应的类型检查。

例如,您不能用number初始化ssn。以下代码将导致错误

let person = new Person(171280926, 'John', 'Doe');Code language: TypeScript (typescript)

总结

  • 使用class关键字在 TypeScript 中定义类。
  • TypeScript 利用 ES6 类语法并添加类型注解,使类更加健壮。
本教程对您有帮助吗?