Within my TypeScript class called Design
, there is a method named checkFetched
. This method's purpose is to verify the existence of a property of type DesignData
within an instance of the class, based on a parameterized type called Filename
. Here is a simplified version of the code:
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
}
}
The checkFetched
method currently returns a boolean value indicating the presence or absence of the specified property. However, I aim to enhance the return type of this method so that when the check is successful, TypeScript infers that the corresponding property is not undefined
, while other properties may still be undefined
.
For instance, after invoking checkFetched('original')
in the loadDesign2
method, TypeScript should recognize that shouldNotHaveUndefined
is not undefined
, but shouldHaveUndefined1
and shouldHaveUndefined2
could potentially be undefined
. At present, shouldHaveUndefined
is treated as non-undefined
.
I have tried various approaches, with the expectation that by refining the return type, TypeScript would correctly infer the existence of the property post calling checkFetched
.
I am reaching out to the community for suggestions on how to tweak this approach to meet my requirements or to ascertain if achieving this goal is inherently unattainable in TypeScript.
To delve further into this topic and share your insights, please visit the TypeScript Playground