静态成员(Static Members)

类可以有静态成员,静态成员跟类实例没有关系,可以通过类本身访问到:

  1. class MyClass {
  2. static x = 0;
  3. static printX() {
  4. console.log(MyClass.x);
  5. }
  6. }
  7. console.log(MyClass.x);
  8. MyClass.printX();

静态成员同样可以使用 public protectedprivate 这些可见性修饰符:

  1. class MyClass {
  2. private static x = 0;
  3. }
  4. console.log(MyClass.x);
  5. // Property 'x' is private and only accessible within class 'MyClass'.

静态成员也可以被继承:

  1. class Base {
  2. static getGreeting() {
  3. return "Hello world";
  4. }
  5. }
  6. class Derived extends Base {
  7. myGreeting = Derived.getGreeting();
  8. }

特殊静态名称(Special Static Names)

类本身是函数,而覆写 Function 原型上的属性通常认为是不安全的,因此不能使用一些固定的静态名称,函数属性像 namelengthcall 不能被用来定义 static 成员:

  1. class S {
  2. static name = "S!";
  3. // Static property 'name' conflicts with built-in property 'Function.name' of constructor function 'S'.
  4. }

为什么没有静态类?(Why No Static Classes?)

TypeScript(和 JavaScript) 并没有名为静态类(static class)的结构,但是像 C# 和 Java 有。

所谓静态类,指的是作为类的静态成员存在于某个类的内部的类。比如这种:

  1. // java
  2. public class OuterClass {
  3. private static String a = "1";
  4. static class InnerClass {
  5. private int b = 2;
  6. }
  7. }

静态类之所以存在是因为这些语言强迫所有的数据和函数都要在一个类内部,但这个限制在 TypeScript 中并不存在,所以也没有静态类的需要。一个只有一个单独实例的类,在 JavaScript/TypeScript 中,完全可以使用普通的对象替代。

举个例子,我们不需要一个 static class 语法,因为 TypeScript 中一个常规对象(或者顶级函数)可以实现一样的功能:

  1. // Unnecessary "static" class
  2. class MyStaticClass {
  3. static doSomething() {}
  4. }
  5. // Preferred (alternative 1)
  6. function doSomething() {}
  7. // Preferred (alternative 2)
  8. const MyHelperObject = {
  9. dosomething() {},
  10. };

类静态块(static Blocks in Classes)

静态块允许你写一系列有自己作用域的语句,也可以获取类里的私有字段。这意味着我们可以安心的写初始化代码:正常书写语句,无变量泄漏,还可以完全获取类中的属性和方法。

  1. class Foo {
  2. static #count = 0;
  3. get count() {
  4. return Foo.#count;
  5. }
  6. static {
  7. try {
  8. const lastInstances = loadLastInstances();
  9. Foo.#count += lastInstances.length;
  10. }
  11. catch {}
  12. }
  13. }

泛型类(Generic Classes)

类跟接口一样,也可以写泛型。当使用 new 实例化一个泛型类,它的类型参数的推断跟函数调用是同样的方式:

  1. class Box<Type> {
  2. contents: Type;
  3. constructor(value: Type) {
  4. this.contents = value;
  5. }
  6. }
  7. const b = new Box("hello!");
  8. // const b: Box<string>

类跟接口一样也可以使用泛型约束以及默认值。

静态成员中的类型参数(Type Parameters in Static Members)

这代码并不合法,但是原因可能并没有那么明显:

  1. class Box<Type> {
  2. static defaultValue: Type;
  3. // Static members cannot reference class type parameters.
  4. }

记住类型会被完全抹除,运行时,只有一个 Box.defaultValue 属性槽。这也意味着如果设置 Box<string>.defaultValue 是可以的话,这也会改变 Box<number>.defaultValue,而这样是不好的。

所以泛型类的静态成员不应该引用类的类型参数。

类运行时的 this(this at Runtime in Classes)

TypeScript 并不会更改 JavaScript 运行时的行为,并且 JavaScript 有时会出现一些奇怪的运行时行为。

就比如 JavaScript 处理 this 就很奇怪:

  1. class MyClass {
  2. name = "MyClass";
  3. getName() {
  4. return this.name;
  5. }
  6. }
  7. const c = new MyClass();
  8. const obj = {
  9. name: "obj",
  10. getName: c.getName,
  11. };
  12. // Prints "obj", not "MyClass"
  13. console.log(obj.getName());

默认情况下,函数中 this 的值取决于函数是如何被调用的。在这个例子中,因为函数通过 obj 被调用,所以 this 的值是 obj 而不是类实例。

这显然不是你所希望的。TypeScript 提供了一些方式缓解或者阻止这种错误。

箭头函数(Arrow Functions)

如果你有一个函数,经常在被调用的时候丢失 this 上下文,使用一个箭头函数或许更好些。

  1. class MyClass {
  2. name = "MyClass";
  3. getName = () => {
  4. return this.name;
  5. };
  6. }
  7. const c = new MyClass();
  8. const g = c.getName;
  9. // Prints "MyClass" instead of crashing
  10. console.log(g());

这里有几点需要注意下:

  • this 的值在运行时是正确的,即使 TypeScript 不检查代码
  • 这会使用更多的内存,因为每一个类实例都会拷贝一遍这个函数。
  • 你不能在派生类使用 super.getName ,因为在原型链中并没有入口可以获取基类方法。

this 参数(this parameters)

在 TypeScript 方法或者函数的定义中,第一个参数且名字为 this 有特殊的含义。该参数会在编译的时候被抹除:

  1. // TypeScript input with 'this' parameter
  2. function fn(this: SomeType, x: number) {
  3. /* ... */
  4. }
  1. // JavaScript output
  2. function fn(x) {
  3. /* ... */
  4. }

TypeScript 会检查一个有 this 参数的函数在调用时是否有一个正确的上下文。不像上个例子使用箭头函数,我们可以给方法定义添加一个 this 参数,静态强制方法被正确调用:

  1. class MyClass {
  2. name = "MyClass";
  3. getName(this: MyClass) {
  4. return this.name;
  5. }
  6. }
  7. const c = new MyClass();
  8. // OK
  9. c.getName();
  10. // Error, would crash
  11. const g = c.getName;
  12. console.log(g());
  13. // The 'this' context of type 'void' is not assignable to method's 'this' of type 'MyClass'.

这个方法也有一些注意点,正好跟箭头函数相反:

  • JavaScript 调用者依然可能在没有意识到它的时候错误使用类方法
  • 每个类一个函数,而不是每一个类实例一个函数
  • 基类方法定义依然可以通过 super 调用

this 类型(this Types)

在类中,有一个特殊的名为 this 的类型,会动态的引用当前类的类型,让我们看下它的用法:

  1. class Box {
  2. contents: string = "";
  3. set(value: string) {
  4. // (method) Box.set(value: string): this
  5. this.contents = value;
  6. return this;
  7. }
  8. }

这里,TypeScript 推断 set 的返回类型为 this 而不是 Box 。让我们写一个 Box 的子类:

  1. class ClearableBox extends Box {
  2. clear() {
  3. this.contents = "";
  4. }
  5. }
  6. const a = new ClearableBox();
  7. const b = a.set("hello");
  8. // const b: ClearableBox

你也可以在参数类型注解中使用 this

  1. class Box {
  2. content: string = "";
  3. sameAs(other: this) {
  4. return other.content === this.content;
  5. }
  6. }

不同于写 other: Box ,如果你有一个派生类,它的 sameAs 方法只接受来自同一个派生类的实例。

  1. class Box {
  2. content: string = "";
  3. sameAs(other: this) {
  4. return other.content === this.content;
  5. }
  6. }
  7. class DerivedBox extends Box {
  8. otherContent: string = "?";
  9. }
  10. const base = new Box();
  11. const derived = new DerivedBox();
  12. derived.sameAs(base);
  13. // Argument of type 'Box' is not assignable to parameter of type 'DerivedBox'.
  14. // Property 'otherContent' is missing in type 'Box' but required in type 'DerivedBox'.

基于 this 的类型保护(this-based type guards)

你可以在类和接口的方法返回的位置,使用 this is Type 。当搭配使用类型收窄 (举个例子,if 语句),目标对象的类型会被收窄为更具体的 Type

  1. class FileSystemObject {
  2. isFile(): this is FileRep {
  3. return this instanceof FileRep;
  4. }
  5. isDirectory(): this is Directory {
  6. return this instanceof Directory;
  7. }
  8. isNetworked(): this is Networked & this {
  9. return this.networked;
  10. }
  11. constructor(public path: string, private networked: boolean) {}
  12. }
  13. class FileRep extends FileSystemObject {
  14. constructor(path: string, public content: string) {
  15. super(path, false);
  16. }
  17. }
  18. class Directory extends FileSystemObject {
  19. children: FileSystemObject[];
  20. }
  21. interface Networked {
  22. host: string;
  23. }
  24. const fso: FileSystemObject = new FileRep("foo/bar.txt", "foo");
  25. if (fso.isFile()) {
  26. fso.content;
  27. // const fso: FileRep
  28. } else if (fso.isDirectory()) {
  29. fso.children;
  30. // const fso: Directory
  31. } else if (fso.isNetworked()) {
  32. fso.host;
  33. // const fso: Networked & FileSystemObject
  34. }

一个常见的基于 this 的类型保护的使用例子,会对一个特定的字段进行懒校验(lazy validation)。举个例子,在这个例子中,当 hasValue 被验证为 true 时,会从类型中移除 undefined

  1. class Box<T> {
  2. value?: T;
  3. hasValue(): this is { value: T } {
  4. return this.value !== undefined;
  5. }
  6. }
  7. const box = new Box();
  8. box.value = "Gameboy";
  9. box.value;
  10. // (property) Box<unknown>.value?: unknown
  11. if (box.hasValue()) {
  12. box.value;
  13. // (property) value: unknown
  14. }

参数属性(Parameter Properties)

TypeScript 提供了特殊的语法,可以把一个构造函数参数转成一个同名同值的类属性。这些就被称为参数属性(parameter properties)。你可以通过在构造函数参数前添加一个可见性修饰符 public private protected 或者 readonly 来创建参数属性,最后这些类属性字段也会得到这些修饰符:

  1. class Params {
  2. constructor(
  3. public readonly x: number,
  4. protected y: number,
  5. private z: number
  6. ) {
  7. // No body necessary
  8. }
  9. }
  10. const a = new Params(1, 2, 3);
  11. console.log(a.x);
  12. // (property) Params.x: number
  13. console.log(a.z);
  14. // Property 'z' is private and only accessible within class 'Params'.

类表达式(Class Expressions)

类表达式跟类声明非常类似,唯一不同的是类表达式不需要一个名字,尽管我们可以通过绑定的标识符进行引用:

  1. const someClass = class<Type> {
  2. content: Type;
  3. constructor(value: Type) {
  4. this.content = value;
  5. }
  6. };
  7. const m = new someClass("Hello, world");
  8. // const m: someClass<string>

抽象类和成员(abstract Classes and Members)

TypeScript 中,类、方法、字段都可以是抽象的(abstract)。

抽象方法或者抽象字段是不提供实现的。这些成员必须存在在一个抽象类中,这个抽象类也不能直接被实例化。

抽象类的作用是作为子类的基类,让子类实现所有的抽象成员。当一个类没有任何抽象成员,他就会被认为是具体的(concrete)。

让我们看个例子:

  1. abstract class Base {
  2. abstract getName(): string;
  3. printName() {
  4. console.log("Hello, " + this.getName());
  5. }
  6. }
  7. const b = new Base();
  8. // Cannot create an instance of an abstract class.

我们不能使用 new 实例 Base 因为它是抽象类。我们需要写一个派生类,并且实现抽象成员。

  1. class Derived extends Base {
  2. getName() {
  3. return "world";
  4. }
  5. }
  6. const d = new Derived();
  7. d.printName();

注意,如果我们忘记实现基类的抽象成员,我们会得到一个报错:

  1. class Derived extends Base {
  2. // Non-abstract class 'Derived' does not implement inherited abstract member 'getName' from class 'Base'.
  3. // forgot to do anything
  4. }

抽象构造签名(Abstract Construct Signatures)

有的时候,你希望接受传入可以继承一些抽象类产生一个类的实例的类构造函数。

举个例子,你也许会写这样的代码:

  1. function greet(ctor: typeof Base) {
  2. const instance = new ctor();
  3. // Cannot create an instance of an abstract class.
  4. instance.printName();
  5. }

TypeScript 会报错,告诉你正在尝试实例化一个抽象类。毕竟,根据 greet 的定义,这段代码应该是合法的:

  1. // Bad!
  2. greet(Base);

但如果你写一个函数接受传入一个构造签名:

  1. function greet(ctor: new () => Base) {
  2. const instance = new ctor();
  3. instance.printName();
  4. }
  5. greet(Derived);
  6. greet(Base);
  7. // Argument of type 'typeof Base' is not assignable to parameter of type 'new () => Base'.
  8. // Cannot assign an abstract constructor type to a non-abstract constructor type.

现在 TypeScript 会正确的告诉你,哪一个类构造函数可以被调用,Derived 可以,因为它是具体的,而 Base 是不能的。

类之间的关系(Relationships Between Classes)

大部分时候,TypeScript 的类跟其他类型一样,会被结构性比较。

举个例子,这两个类可以用于替代彼此,因为它们结构是相等的:

  1. class Point1 {
  2. x = 0;
  3. y = 0;
  4. }
  5. class Point2 {
  6. x = 0;
  7. y = 0;
  8. }
  9. // OK
  10. const p: Point1 = new Point2();

类似的还有,类的子类型之间可以建立关系,即使没有明显的继承:

  1. class Person {
  2. name: string;
  3. age: number;
  4. }
  5. class Employee {
  6. name: string;
  7. age: number;
  8. salary: number;
  9. }
  10. // OK
  11. const p: Person = new Employee();

这听起来有些简单,但还有一些例子可以看出奇怪的地方。

空类没有任何成员。在一个结构化类型系统中,没有成员的类型通常是任何其他类型的父类型。所以如果你写一个空类(只是举例,你可不要这样做),任何东西都可以用来替换它:

  1. class Empty {}
  2. function fn(x: Empty) {
  3. // can't do anything with 'x', so I won't
  4. }
  5. // All OK!
  6. fn(window);
  7. fn({});
  8. fn(fn);