有没有一种方法可以通过使用函数进行检查来实现类型缩小


class A {}
class B extends A {
bb() { ... }
}
function isB(obj: A) {
return obj instanceof B;
}
const x: A = new B(); // x has type A
if (isB(x)) {
x.bb(); // can I get x to have type B?
}

我知道,如果我有x instanceof B在这种情况下,它会起作用。但是我可以通过isB()吗?

Typescript通过一个特殊的返回类型X is A支持这一点。你可以在他们关于用户定义类型保护的章节中阅读更多关于这方面的内容。

例如,您可以这样键入:

class A {}
class B extends A {
bb() { ... }
}
function isB(obj: A): obj is B { // <-- note the return type here
return obj instanceof B;
}
const x: A = new B(); // x has type A
if (isB(x)) {
x.bb(); // x is now narrowed to type B
}

最新更新