假设我们有一个类似于以下的类:
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()
不会是undefined
。
这基于Firestore DocumentSnapshot
's API,其中您具有exists
属性和data
方法。但是,为了确保data()
不是undefined
,我们需要执行以下操作:
const data = result.data()
if (data) {
// do something with data
}
答案 0 :(得分:1)
不具有属性,但是如果您可以将该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()
}
答案 1 :(得分:0)
否,但是您可以使用!
operator告诉编译器您正在做什么:
if (rawResult.exists()) {
const result = rawResult.decode()! // always a Result
}