我有一个名为Design
的TypeScript类,它包含一个名为checkFetched
的方法.此方法被设计为基于称为Filename
的参数化类型来判断类实例中是否存在类型DesignData
的属性.下面是代码的简化版本:
type Filename = 'original' | 'result'
type DesignData = {
id: string
// ...
}
export class Design {
original?: DesignData
result?: DesignData
checkFetched(target: Filename): this is { [K in typeof target]: DesignData } {
return !!this[target]
}
private async loadDesign(fileName: Filename) {
if (!this.checkFetched(fileName)) return
const shouldNotHaveUndefined = this[fileName]
const shouldHaveUndefined1 = this.original
const shouldHaveUndefined2 = this.result
}
private async loadDesign2() {
if (!this.checkFetched('original')) return
const shouldNotHaveUndefined = this.original
const shouldHaveUndefined = this.result
}
}
checkFetched
方法返回一个布尔值,指示指定的属性是否存在.但是,我想优化这个方法的返回类型,如果判断通过,TypeScript应该推断相应的属性不是undefined
,而其他属性仍然可以是undefined
.
例如,在loadDesign2
方法中调用checkFetched('original')
后,TypeScript应该理解shouldNotHaveUndefined
不是undefined
,但shouldHaveUndefined1
和shouldHaveUndefined2
可以是undefined
.现在,shouldHaveUndefined
将被视为不是undefined
.
考虑到我的try ,我希望通过细化返回类型,TypeScript在调用checkFetched
后能正确推断出属性的存在.
我正在寻求社区的见解,以确定这种方法是否可以修改以满足我的需求,或者这种要求是否本质上不可能在TypeScript中实现.
请使用此TypeScript Playground链接探索和分享您的见解:TypeScript Playground