不传递参数的用户定义类型保护

User defined type guards without passing a parameter

假设我有这些 类:

export abstract class AbstractSubjectChild<T extends Subject>
{
    protected parent: T | undefined;

    public hasParent()
    {
        return this.parent != null;
    }

    public setParent(parent: T): void
    {
        this.parent = parent;
    }

    public getParent(): T | undefined
    {
        return this.parent;
    }
}

class Child extends AbstractSubjectChild<Post>
{   
}

我想做这样的事情:

const child = new Child();

if (child.hasParent()) {
    const post: Post = child.getParent();
}

有没有办法告诉 TS 编译器根据 hasParent() 结果推断类型,而不必到处显式使用 as Post

export abstract class AbstractSubjectChild<T extends Subject>
{
    protected _parent?: T;

    public set parent(parent: T): void
    {
        this._parent = parent;
    }

    public get parent(): T | undefined
    {
        return this._parent;
    }
}

这样写你的 class 你可以这样做:

if (child.parent) {
  const post = child.parent;
  // everywhere in this block scope is now aware of the type of post
}