Skip to content

this类型

在类中,一个叫做 this 的特殊类型动态地指向当前类的类型。让我们来看看这有什么用:

typescript
class Box { 
  contents: string = ""; 
  // (method) Box.set(value: string): this 
  set(value: string) { 
    this.contents = value; 
    return this; 
  } 
}

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

typescript
class ClearableBox extends Box { 
  clear() { 
    this.contents = ""; 
  } 
}
const a = new ClearableBox();

// const b: ClearableBox 
const b = a.set("hello"); 
console.log(b)

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

typescript
class Box { 
  content: string = ""; 
  sameAs(other: this) { 
    return other.content === this.content; 
  } 
}
const box = new Box() 
console.log(box.sameAs(box))

这与其他写法不同:Box,如果你有一个派生类,它的 sameAs 方法现在只接受该同一派生类的其他实例。

typescript
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(); 
derived.sameAs(base);