This类型可以在子类调用的时候,变成子类的类型,所以可以用来作为子类类型检查的工具。
一个用法就是用来验证可选参数是否有值。
class Box {
value?: T;
hasValue(): this is { value: T} {
return this.value !== undefined;
}
}
const box = new Box();
这里box.value有可能是undefined,所以不能赋给string类型的t。
但是使用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;
}
这个语法糖必须学会,因为不会的话,看很多代码就会觉得很奇怪。
只要你在定义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();
在constructor里面定义了name和age,就相当于在class里面定义个name和age的字段。
留言与评论(共有 0 条评论) “” |