TypeScript学习42

This类型

在TypeScript里面,this还可以表示所在对象的类型。

比如下面的代码:

class MyClass {
    getThisType() {
        return this;
    }
}

class DerivedClass extends MyClass {
};

const a: DerivedClass = new DerivedClass();
console.log(a.getThisType());


TypeScript学习42

运行结果:


TypeScript学习42

也可以用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));


TypeScript学习42

这个和直接使用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));


TypeScript学习42

这里由于b变量是Box类型,所以编译器就直接报错了。


TypeScript学习42

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章