hackftz

bits change world

导航

深入理解TypeScript——文档篇之类

Posted on 2020-10-01 19:41  hackftz  阅读(102)  评论(0编辑  收藏  举报

一、js和ts类的区别

       js是基于类的面向对象方式,构建父子类的继承结构,写起来不简洁,也不形象。ts则是以简洁明了的方式实现类的定义、继承、扩展等等。

      之前我也提过,js最终会登录浏览器平台,但是至少不是现在,所以在下一个js时代之前,我们需要定ts来规范当前的客户端代码。

二、用ts实现类

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

三、继承

       使用extends 关键字来继承。

class Animal { // Animal是基类,也叫超类
    move(distanceInMeters: number = 0) {
        console.log(`Animal moved ${distanceInMeters}m.`);
    }
}

class Dog extends Animal { // Dog是派生自Animal的派生类,也叫子类
    bark() {
        console.log('Woof! Woof!');
    }
}

const dog = new Dog();
dog.bark();
dog.move(10);

       派生类的构造函数必须包含 "super" 调用。这是ts强制执行的一条重要规则。

// 如果父类下没有构造函数,如下
class Animal {
  move(distanceInMeters: number = 0) {

  }
}

class Snake extends Animal {
  constructor(name: string) {
    super() // 如果父类没有定义构造函数,父类会有默认值,什么都不做,但是子类必须要在构造函数中调用super
  }
  move(distanceInMeters = 5) {
      console.log("Slithering...");
      super.move(distanceInMeters);
  }
}

let sam = new Snake("Sammy the Python");

console.log(sam);

// 父类含有构造函数
class Animal {
    name: string;
    constructor(theName: string) { // 在子类中执行基类的构造函数
        this.name = theName; 
    }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

let sam = new Snake("Sammy the Python");
sam.move();

四、公共、私有与受保护的修饰符

public

       前置定义,ts里可以不写即为默认为public,可以自由的访问定义的值。

private

       不能再声明它的类的外部被访问。即为私有属性。

protected

       protected修饰符与 private修饰符的行为很相似,但有一点不同, protected成员在派生类中仍然可以访问,但是注意:依然不能在类的外面被访问。

class Person {
    protected name: string;
    constructor(name: string) { this.name = name; }
}

class Employee extends Person {
    private department: string;

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

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // 错误

       构造函数也可以被标记成 protected。 这意味着这个类不能在包含它的类外被实例化,但是能被继承。

// 类属性 name、constructor => protected
class Person {
    protected name: string;
    protected constructor(theName: string) { this.name = theName; }
}

// Employee 能够继承 Person
class Employee extends Person {
    private department: string;

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

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
let john = new Person("John"); // 类“Person”的构造函数是受保护的,仅可在类声明中访问。

// 类属性 name => not protected, constructor => protected
class Person {
  protected name: string;
  constructor(theName: string) { this.name = theName; }
}

// Employee 能够继承 Person
class Employee extends Person {
  private department: string;

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

  public getElevatorPitch() {
      return `Hello, my name is ${this.name} and I work in ${this.department}.`;
  }
}

let howard = new Employee("Howard", "Sales");
let john = new Person("John");
console.log(john.name); // 属性“name”受保护,只能在类“Person”及其子类中访问。ts(2445)

五、readonly修饰符

       使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。

class Octopus {
    readonly name: string;
    readonly numberOfLegs: number = 8;
    constructor (theName: string) {
        this.name = theName;
    }
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.

       参数属性:参数属性可以方便地让我们在一个地方定义并初始化一个成员。

class Octopus {
    readonly numberOfLegs: number = 8;
    constructor(readonly name: string) { // 声明并初始化一个私有成员
    }
}

// 等价于
class Octopus {
    readonly name: string;
    readonly numberOfLegs: number = 8;
    constructor (theName: string) {
        this.name = theName;
    }
}

六、存取器

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();

console.log(employee.fullName); // Property '_fullName' has no initializer and is not definitely assigned in the constructor.  

employee.fullName = "Bob Smith";

if (employee.fullName) {
    console.log(employee.fullName);
}

注意:

  • 存取器要求你将编译器设置为输出ECMAScript 5或更高。 不支持降级到ECMAScript 3。
  • 其次,只带有 get不带有 set的存取器自动被推断为 readonly

七、静态属性

       这些属性存在于类本身上面而不是类的实例上。

class Grid {
    static origin = {x: 0, y: 0};
    calculateDistanceFromOrigin(point: {x: number; y: number;}) {
        let xDist = (point.x - Grid.origin.x); // 如同在实例属性上使用 this.前缀来访问属性一样,这里我们使用 Grid.来访问静态属性。
        let yDist = (point.y - Grid.origin.y);
        return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;
    }
    constructor (public scale: number) { }
}

八、抽象类

       抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。

       不同于接口,抽象类可以包含成员的实现细节。 abstract关键字是用于定义抽象类和在抽象类内部定义抽象方法。

abstract class Animal {
    abstract makeSound(): void;
    move(): void {
        console.log('roaming the earch...');
    }
}

       抽象类中的抽象方法不包含具体实现并且必须在派生类中实现。 抽象方法的语法与接口方法相似。 两者都是定义方法签名但不包含方法体。 然而,抽象方法必须包含 abstract关键字并且可以包含访问修饰符。

abstract class Department {

  constructor(public name: string, age: number = 10) { // 如果age这里不用public定义,则它是一个局部变量,不能从实例的this.上获取到
  }

  printName(): void {
      console.log('Department name: ' + this.name);
  }

  abstract printMeeting(): void; // 必须在派生类中实现
}

class AccountingDepartment extends Department {

  constructor() {
      super('Accounting and Auditing'); // 在派生类的构造函数中必须调用 super()
  }

  printMeeting(): void {
      console.log('The Accounting Department meets each Monday at 10am.');
  }

  generateReports(): void {
      console.log('Generating accounting reports...');
  }
}

let department: Department; // 允许创建一个对抽象类型的引用
// department = new Department(); // 错误: 不能创建一个抽象类的实例
department = new AccountingDepartment(); // 允许对一个抽象子类进行实例化和赋值
console.log(department.name); // Accounting and Auditing
console.log(department.age); // 类型“Department”上不存在属性“age”。
department.printName();
department.printMeeting();
// department.generateReports(); // 错误: 方法在声明的抽象类中不存在

       注意上面标记*处: Typescript 提供的简写形式 — 用构造函数的参数直接定义属性。

九、高级技巧

  1. 构造函数

    class Greeter {
        static standardGreeting = "Hello, there";
        greeting: string;
        greet() {
            if (this.greeting) {
                return "Hello, " + this.greeting;
            }
            else {
                return Greeter.standardGreeting;
            }
        }
    }
    
    let greeter1: Greeter;
    greeter1 = new Greeter();
    console.log(greeter1.greet());
    
    let greeterMaker: typeof Greeter = Greeter; // Greeter类的类型,而不是实例的类型。
    greeterMaker.standardGreeting = "Hey there!";
    
    let greeter2: Greeter = new greeterMaker();
    console.log(greeter2.greet());
    
  2. 把类当作接口

    因为类可以创建出类型,所以你能够在允许使用接口的地方使用类。

    简而言之,就是把类当成接口来用。

    class Point {
        x: number;
        y: number;
    }
    
    interface Point3d extends Point {
        z: number;
    }
    
    let point3d: Point3d = {x: 1, y: 2, z: 3};