Typescript 物业护卫员

Typescript 物业护卫员,typescript,google-cloud-firestore,Typescript,Google Cloud Firestore,假设我们有一个类,如下所示: class RawResult { private raw: string | undefined; get exists(): boolean { return this.raw !== undefined; } decode(): Result | undefined { if (this.raw === undefined) { return undefined; } return someExpe

假设我们有一个类,如下所示:

class RawResult {
  private raw: string | undefined;
  get exists(): boolean {
    return this.raw !== undefined;
  }
  decode(): Result | undefined {
    if (this.raw === undefined) {
       return undefined;
    }
    return someExpensiveDecoding(this.raw); 
  }
}
有没有办法告诉TS编译器,
result.exists
意味着
result.decode()
不会是
未定义的

这是基于,其中有
exists
属性和
data
方法。但是,为了确保
data()
不是未定义的

const data = result.data()
if (data) {
   // do something with data
}

不,但您可以告诉编译器您知道您正在使用:


不使用属性,但如果可以将该getter转换为普通方法,则可以按如下方式执行:

type Result = {}

interface RawResultExists extends RawResult {
    decode(): Result
}

class RawResult {
    private raw: string | undefined;
    exists(): this is RawResultExists {
        return this.raw !== undefined;
    }
    decode() {
        if (this.raw === undefined) {
            return undefined;
        }
        return this.raw as Result
    }
}

const rawResult = new RawResult();

if (rawResult.exists()) {
    const data = rawResult.decode()
}


这里有一个关于属性不支持typeguards的问题
type Result = {}

interface RawResultExists extends RawResult {
    decode(): Result
}

class RawResult {
    private raw: string | undefined;
    exists(): this is RawResultExists {
        return this.raw !== undefined;
    }
    decode() {
        if (this.raw === undefined) {
            return undefined;
        }
        return this.raw as Result
    }
}

const rawResult = new RawResult();

if (rawResult.exists()) {
    const data = rawResult.decode()
}