本篇翻译整理自 TypeScript Handbook 中 「Classes」 章节。
静态成员(Static Members)
类可以有静态成员,静态成员跟类实例没有关系,可以通过类本身访问到
class MyClass {
static x = 0;
static printX() {
console.log(MyClass.x);
}
}
console.log(MyClass.x);
MyClass.printX();
静态成员同样可以使用 public protected 和 private 这些可见性修饰符
class MyClass {
private static x = 0;
}
console.log(MyClass.x);
// Property 'x' is private and only accessible within class 'MyClass'.
和JavaScript一样,静态成员也可以被继承
class Base {
static getGreeting() {
return "Hello world";
}
}
class Derived extends Base {
myGreeting = Derived.getGreeting();
}
特殊静态名称
类本身是函数,而覆写 Function 原型上的属性通常认为是不安全的
因此函数属性像 name、length、call 不能被用来定义 static 成员
class S {
static name = "S!";
// Static property 'name' conflicts with built-in property 'Function.name' of constructor function 'S'.
}
类静态块
静态块允许你写一系列有自己作用域的语句,也可以获取类里的私有字段。
这意味着我们可以安心的写初始化代码:正常书写语句,无变量泄漏,还可以完全获取类中的属性和方法。
class Foo {
static #count = 10;
get count() {
return Foo.#count;
}
// 类初始化的时候,会自动执行
static {
try {
console.log(this.#count)
}
catch {}
}
}
泛型类
类跟接口一样,也可以写泛型。当使用 new 实例化一个泛型类,它的类型参数的推断跟函数调用是同样的方式
class Box<Type> {
contents: Type;
constructor(value: Type) {
this.contents = value;
}
}
const b = new Box("hello!");
// const b: Box<string>
泛型类的静态成员不应该引用类的类型参数,
class Box<Type> {
static defaultValue: Type; // error
// Static members cannot reference class type parameters.
}
this 参数
在 TypeScript 方法或者函数的定义中,第一个参数且名字为 this 有特殊的含义。该参数会在编译的时候被抹除:
// TypeScript input with 'this' parameter
function fn(this: SomeType, x: number) {
/* ... */
}
// JavaScript output
function fn(x) {
/* ... */
}
TypeScript 会检查一个有 this 参数的函数在调用时是否有一个正确的上下文。不像上个例子使用箭头函数,我们可以给方法定义添加一个 this 参数,静态强制方法被正确调用:
class MyClass {
name = "MyClass";
getName(this: MyClass) {
return this.name;
}
}
const c = new MyClass();
// OK
c.getName();
// Error, would crash
const g = c.getName;
console.log(g());
// The 'this' context of type 'void' is not assignable to method's 'this' of type 'MyClass'.
箭头函数和this参数
箭头函数
class MyClass {
name = "MyClass";
getName = () => {
return this.name;
};
}
const c = new MyClass();
const g = c.getName;
// Prints "MyClass" instead of crashing
console.log(g());
箭头函数也可以正确修正this指向,但有几点需要注意:
this的值在运行时是正确的,即使 TypeScript 不检查代码- 这会使用更多的内存,因为箭头函数会被作为变量使用,而不是函数,因此每一个类实例都会拷贝一遍这个函数
- 不可以通过
super来调用基类方法, 因为如果使用箭头函数定义方法的时候,其是被定义在了实例成员本身上,而super指代的是父类的原型对象,所以此时是无法在super对象上找到对应的基类方法的
this参数
class MyClass {
name = "MyClass";
getName(this: MyClass) {
return this.name;
};
}
const c = new MyClass();
console.log(c.getName());
this参数也有一些注意点:
- 每个类一个函数,而不是每一个类实例一个函数
- 基类方法定义依然可以通过
super调用
this 类型
在类中,有一个特殊的名为 this 的类型,会动态的引用当前类的类型
class Box {
contents: string = "";
set(value: string) {
// (method) Box.set(value: string): this
// 表示返回值是Box的实例或Box子类的实例对象
this.contents = value;
return this;
}
}
class Box {
content: string = "";
sameAs(other: this) {
return other.content === this.content;
}
}
class DerivedBox extends Box {
otherContent: string = "?";
}
const base = new Box();
const derived = new DerivedBox();
// success 此时的this表示的是Box的实例及其子类的实例,所以derived可以正常被传入
console.log(base.sameAs(derived))
// error 此时的this表示的是DerivedBox的实例及其子类实例,而base是DerivedBox父类的实例
console.log(derived.sameAs(base))
基于 this 的类型保护
你可以在类和接口的方法返回的位置,使用 this is Type(类型谓词) 。
当搭配使用类型收窄 (举个例子,if 语句),目标对象的类型会被收窄为更具体的 Type
class Box<T> {
value?: T;
hasValue(): this is { value: T } {
return this.value !== undefined;
}
}
const box = new Box();
box.value = "Gameboy";
box.value;
// (property) Box<unknown>.value?: unknown
// 此时就可以确保box的value属性一定是有值的
if (box.hasValue()) {
box.value; // box的类型为 Box 和 { value: T }的交叉类型
// (property) value: unknown
}
另一个例子
class FileSystemObject {
isFile(): this is FileRep {
return this instanceof FileRep;
}
isDirectory(): this is Directory {
return this instanceof Directory;
}
isNetworked(): this is Networked & this {
return this.networked;
}
constructor(public path: string, private networked: boolean) {}
}
class FileRep extends FileSystemObject {
constructor(path: string, public content: string) {
super(path, false);
}
}
class Directory extends FileSystemObject {
children: FileSystemObject[] = [];
}
interface Networked {
host: string;
}
const fso: FileSystemObject = new FileRep("foo/bar.txt", "foo");
if (fso.isFile()) {
fso.content;
// const fso: FileRep
} else if (fso.isDirectory()) {
fso.children;
// const fso: Directory
} else if (fso.isNetworked()) {
fso.host;
// const fso: Networked & FileSystemObject
// 因为foo首先一定是FileSystemObject或其子类的实例,且必须有一个host属性,所以就变成了交叉类型
}
参数属性
TypeScript 提供了特殊的语法,可以把一个构造函数参数转成一个同名同值的类属性。这些就被称为参数属性(parameter properties)。
可以通过在构造函数参数前添加一个可见性修饰符 public private protected 或者 readonly 来创建参数属性,最后这些类属性字段也会得到这些修饰符
class Params {
constructor(
public readonly x: number,
protected y: number,
private z: number
) {
// No body necessary
}
}
const a = new Params(1, 2, 3);
console.log(a.x);
// (property) Params.x: number
console.log(a.z);
// Property 'z' is private and only accessible within class 'Params'.
类表达式
类表达式跟类声明非常类似,唯一不同的是类表达式不需要一个名字,尽管我们可以通过绑定的标识符进行引用
const someClass = class<Type> {
content: Type;
constructor(value: Type) {
this.content = value;
}
};
const m = new someClass("Hello, world");
// const m: someClass<string>
抽象类和成员
TypeScript 中,类、方法、字段都可以是抽象的(abstract)。
抽象方法或者抽象字段是不提供实现的。这些成员必须存在在一个抽象类中,这个抽象类也不能直接被实例化。
抽象类的作用是作为子类的基类,让子类实现所有的抽象成员。当一个类没有任何抽象成员,他就会被认为是具体类
abstract class Base {
abstract getName(): string;
printName() {
console.log("Hello, " + this.getName());
}
}
// const b = new Base(); // error
// Cannot create an instance of an abstract class.
// 我们不能使用 `new` 实例 `Base` 因为它是抽象类。我们需要写一个派生类,并且实现抽象成员
class Derived extends Base {
getName() {
return "world";
}
}
const d = new Derived();
d.printName();
抽象构造签名
有的时候,你希望接受传入可以继承一些抽象类产生一个类的实例的类构造函数。
abstract class Base {
abstract getName(): string;
printName() {
console.log("Hello, " + this.getName());
}
}
class Derived extends Base {
getName() {
return "world";
}
}
// typeof Base 意味着传入的类型必须是Base的实例,也就是一个抽象类
function greet(ctor: typeof Base) {
const instance = new ctor();
// Cannot create an instance of an abstract class.
instance.printName();
}
但如果你写一个函数接受传入一个构造签名
abstract class Base {
abstract getName(): string;
printName() {
console.log("Hello, " + this.getName());
}
}
class Derived extends Base {
getName() {
return "world";
}
}
// 返回值如果是Base类型,那么表示的是返回值类型可以是Base及其子类的实例对象
function greet(ctor: new () => Base) {
const instance = new ctor();
instance.printName();
}
greet(Derived); // success
greet(Base); // error
类之间的关系
大部分时候,TypeScript 的类跟其他类型一样,会被结构性比较
class Point1 {
x = 0;
y = 0;
}
class Point2 {
x = 0;
y = 0;
}
// OK --- 这两个类可以用于替代彼此,因为它们结构是相等的
const p: Point1 = new Point2();
类似的还有,类的子类型之间可以建立关系,即使没有明显的继承:
class Person {
name: string;
age: number;
}
class Employee {
name: string;
age: number;
salary: number;
}
// OK
const p: Person = new Employee();
空类没有任何成员。在一个结构化类型系统中,没有成员的类型通常是任何其他类型的父类型。所以如果你写一个空类(只是举例,你可不要这样做),任何东西都可以用来替换它
class Empty {}
function fn(x: Empty) { }
// All OK!
fn(window);
fn({});
fn(fn);