TypeScript学习43

使用this类型来做类型检查

This类型可以在子类调用的时候,变成子类的类型,所以可以用来作为子类类型检查的工具。

一个用法就是用来验证可选参数是否有值。

class Box {
    value?: T;
    hasValue(): this is { value: T} {
        return this.value !== undefined;
    }
}

const box = new Box();


TypeScript学习43

这里box.value有可能是undefined,所以不能赋给string类型的t。


TypeScript学习43

但是使用hasValue()判断过,就能去除undefined的可能性。

class Box {
    value?: T;
    hasValue(): this is { value: T} {
        return this.value !== undefined;
    }
}

const box = new Box();

if(box.hasValue()) {
    const t: string = box.value;
}


TypeScript学习43

参数属性

这个语法糖必须学会,因为不会的话,看很多代码就会觉得很奇怪。

只要你在定义constructor参数的时候,加上public/private/protected或者readonly,这么这些参数就会自动声明成对应的字段,而不需要额外声明。

class Params {
    constructor(public name: string, private age: number) {

    }

    getAge() {
        console.log("Age: " + this.age);
    }
}

const p: Params = new Params('abc', 26);

console.log(p.name);
p.getAge();


TypeScript学习43

在constructor里面定义了name和age,就相当于在class里面定义个name和age的字段。

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

相关文章

推荐文章