Typeguard可缩小此的属性



有没有一种语法可以让类型保护窄如this['some_property']

我知道把缩小目标作为一个论点是可能的,但我想也许我可以稍微澄清一下。

type A = {a: number};
type B = {b: string};
class Foo {
union_member: A | B;
constructor(val: A | B) { this.union_member = val; }
narrow_a() : this['union_member'] is A { // invalid
return true;
}
also_no({union_member} : this = this) : union_member is A { // invalid
return true;
}
goal() {
if (this.narrow_a()) {
this.union_member.a + 42 /* ... */;
}
}
}

您不能对单个字段进行保护,但如果我们定义了一个合适的接口,则对this进行保护就足够了。

interface UnionIsA {
union_member: A;
}

然后我们可以把narrow_a写成

narrow_a() : this is UnionIsA {
return true;
}

现在将编译goal。(注意,您必须执行this.narrow_a(),而不仅仅是narrow_a();这是一个Javascript怪癖,与类型系统无关(

goal() {
if (this.narrow_a()) {
this.union_member.a + 42 /* ... */;
}
}

最新更新