在TypeScript里面,this还可以表示所在对象的类型。
比如下面的代码:
class MyClass {
getThisType() {
return this;
}
}
class DerivedClass extends MyClass {
};
const a: DerivedClass = new DerivedClass();
console.log(a.getThisType());
运行结果:
也可以用this,来作为参数的类型。
class Box {
content: string = '';
sameAs(other: this) {
return this.content === other.content;
}
}
const a = new Box();
const b = new Box();
console.log(a.sameAs(b));
这个和直接使用Box,并不一样。
如果有类继承,那么子类的sameAs的other参数类型则是子类的类型。
class Box {
content: string = '';
sameAs(other: this) {
return this.content === other.content;
}
}
class Derived extends Box {
msg: string = '';
};
const a = new Derived();
const b = new Box();
console.log(a.sameAs(b));
这里由于b变量是Box类型,所以编译器就直接报错了。
留言与评论(共有 0 条评论) “” |