typescript 类定义-TypeScript 中类的使用§

2023-09-01 0 4,153 百度已收录

种类

传统方式下,JavaScript通过构造函数实现类的概念,通过原型链实现继承。 在 ES6 中,我们终于有了类。

除了实现 ES6 中类的所有功能之外,TypeScript 还添加了一些新的用法。

本节主要介绍类的用法,下一节将介绍如何定义类的类型。

阶级的概念

虽然JavaScript中有类的概念,但是大多数JavaScript程序员可能对类不是很熟悉。 这里简单介绍一下类相关的概念。

ES6 中类的使用

我们先回顾一下ES6中类的用法,更详细的介绍可以参考它。

属性和技能

使用class来定义类,使用constructor来定义构造函数

当new生成一个新的实例时,会手动调用构造函数。

class Animal {
    name;
    constructor(name) {
        this.name = name;
    }
    sayHi() {
        return `My name is ${this.name}`;
    }
}
let a = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack

typescript 类定义-TypeScript 中类的使用§

类继承

使用extends关键字实现继承typescript 类定义,在子类中使用super关键字调用父类的构造函数和技巧。

class Cat extends Animal {
  constructor(name) {
    super(name); // 调用父类的 constructor(name)
    console.log(this.name);
  }
  sayHi() {
    return 'Meow, ' + super.sayHi(); // 调用父类的 sayHi()
  }
}
let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom

存取器

使用 getter 和 setter 来更改形式参数和属性的读取行为:

class Animal {
  constructor(name) {
    this.name = name;
  }
  get name() {
    return 'Jack';
  }
  set name(value) {
    console.log('setter: ' + value);
  }
}
let a = new Animal('Kitty'); // setter: Kitty
a.name = 'Tom'; // setter: Tom
console.log(a.name); // Jack

静态方法

使用static修饰符的方式称为静态方式,它们不需要实例化,而是直接通过类调用:

class Animal {
  static isAnimal(a) {
    return a instanceof Animal;
  }
}
let a = new Animal('Jack');
Animal.isAnimal(a); // true
a.isAnimal(a); // TypeError: a.isAnimal is not a function

ES7 中类的使用

ES7 中有一些关于类的提案,TypeScript 也实现了它们。 这里简单介绍一下。

实例属性

在ES6中,实例属性只能通过构造函数中的this.xxx来定义。 在ES7提案中,它们可以直接在类上定义:

class Animal {
  name = 'Jack';
  constructor() {
    // ...
  }
}
let a = new Animal();
console.log(a.name); // Jack

静态属性

在ES7提案中,可以使用static来定义静态属性:

class Animal {
  static num = 42;
  constructor() {
    // ...
  }
}
console.log(Animal.num); // 42

TypeScript 中类的使用 public private 和 protected

TypeScript 可以使用三种访问修饰符(Access Modifiers),即 public、private 和 protected。

这里有些例子:

class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
}
let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom

在上面的示例中,name 设置为 public,因此允许直接访问实例的 name 属性。

很多时候,我们希望有些属性很难直接访问。 在这种情况下,我们可以使用私有:

class Animal {
  private name;
  public constructor(name) {
    this.name = name;
  }
}
let a = new Animal('Jack');
console.log(a.name);
a.name = 'Tom';
// index.ts(9,13): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
// index.ts(10,1): error TS2341: Property 'name' is private and only accessible within class 'Animal'.

需要注意的是,TypeScript 编译的代码并不限制私有属性的外部可访问性。

上面例子的编译后的代码是:

var Animal = (function () {
  function Animal(name) {
    this.name = name;
  }
  return Animal;
})();
var a = new Animal('Jack');
console.log(a.name);
a.name = 'Tom';

用 private 修饰的属性或方法不允许在基类中访问:

class Animal {
  private name;
  public constructor(name) {
    this.name = name;
  }
}
class Cat extends Animal {
  constructor(name) {
    super(name);
    console.log(this.name);
  }
}
// index.ts(11,17): error TS2341: Property 'name' is private and only accessible within class 'Animal'.

而如果用protected修饰的话,就允许在泛型中访问:

class Animal {
  protected name;
  public constructor(name) {
    this.name = name;
  }
}
class Cat extends Animal {
  constructor(name) {
    super(name);
    console.log(this.name);
  }
}

当构造函数修改为private时,该类不允许被继承或实例化:

class Animal {
  public name;
  private constructor(name) {
    this.name = name;
  }
}
class Cat extends Animal {
  constructor(name) {
    super(name);
  }
}
let a = new Animal('Jack');
// index.ts(7,19): TS2675: Cannot extend a class 'Animal'. Class constructor is marked as private.
// index.ts(13,9): TS2673: Constructor of class 'Animal' is private and only accessible within the class declaration.

当构造函数被修改为protected时,该类只允许被继承:

class Animal {
  public name;
  protected constructor(name) {
    this.name = name;
  }
}
class Cat extends Animal {
  constructor(name) {
    super(name);
  }
}
let a = new Animal('Jack');
// index.ts(13,9): TS2674: Constructor of class 'Animal' is protected and only accessible within the class declaration.

参数属性

typescript 类定义-TypeScript 中类的使用§

构造函数参数中也可以使用修饰符和readonly,相当于在类中定义了属性,给属性赋予了形参,让代码更加简洁。

class Animal {
  // public name: string;
  public constructor(public name) {
    // this.name = name;
  }
}

只读

只读属性关键字只允许出现在属性声明或索引签名或构造函数中。

class Animal {
  readonly name;
  public constructor(name) {
    this.name = name;
  }
}
let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property.

注意,如果readonly和其他访问修饰符同时存在typescript 类定义,则需要将它们写在它们的旁边。

class Animal {
  // public readonly name;
  public constructor(public readonly name) {
    // this.name = name;
  }
}

抽象类

Abstract 用于定义抽象类及其内部的表示技术。

什么是抽象类?

首先,抽象类是不允许被实例化的:

abstract class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
  public abstract sayHi();
}
let a = new Animal('Jack');
// index.ts(9,11): error TS2511: Cannot create an instance of the abstract class 'Animal'.

typescript 类定义-TypeScript 中类的使用§

在上面的例子中,我们定义了一个抽象类Animal和一个具体方法sayHi。 实例化抽象类时报错。

其次,抽象类中的具体方法必须通用实现:

abstract class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
  public abstract sayHi();
}
class Cat extends Animal {
  public eat() {
    console.log(`${this.name} is eating.`);
  }
}
let cat = new Cat('Tom');
// index.ts(9,7): error TS2515: Non-abstract class 'Cat' does not implement inherited abstract member 'sayHi' from class 'Animal'.

上面的例子中,我们定义了一个继承抽象类Animal的类Cat,但是没有实现具体方法sayHi,所以报了编译错误。

这是正确使用抽象类的示例:

abstract class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
  public abstract sayHi();
}
class Cat extends Animal {
  public sayHi() {
    console.log(`Meow, My name is ${this.name}`);
  }
}
let cat = new Cat('Tom');

上面的例子中,我们实现了具体方法sayHi,并且编译通过了。

需要注意的是,即使在具体模式下,该类仍然会存在于 TypeScript 的编译结果中。 上述代码的编译结果为:

var __extends =
  (this && this.__extends) ||
  function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() {
      this.constructor = d;
    }
    d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __());
  };
var Animal = (function () {
  function Animal(name) {
    this.name = name;
  }
  return Animal;
})();
var Cat = (function (_super) {
  __extends(Cat, _super);
  function Cat() {
    _super.apply(this, arguments);
  }
  Cat.prototype.sayHi = function () {
    console.log('Meow, My name is ' + this.name);
  };
  return Cat;
})(Animal);
var cat = new Cat('Tom');

班级类型

将 TypeScript 类型添加到类中很容易,类似于套接字:

class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  sayHi(): string {
    return `My name is ${this.name}`;
  }
}
let a: Animal = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack

参考

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悟空资源网 typescript typescript 类定义-TypeScript 中类的使用§ https://www.wkzy.net/game/187849.html

常见问题

相关文章

官方客服团队

为您解决烦忧 - 24小时在线 专业服务