I am writing a class, and in the constructor, the class class calls one of its methods toJSON
, and assigns the return value to an instance property:
class Example {
property;
snapshot;
constructor(){
this.property = 'property'
if (Math.random() < 0.5){
this.snapshot = this.toJSON()
}
}
toJSON(){
return {
this: 'this',
is: 'is',
a: 'a',
sample: 'sample',
json: 'json'
}
}
useSnapshot(){
console.log(this.snapshot?.nope)
}
}
As I work on this, the shape of the return value of toJSON
may change, so I don't want to hardcode a return type. However, I would expect typescript to infer a return type and them enforce it. So in the above example, this.snapshot.nope
will error, because nope
does not exist on the return type of toJSON
, and therefore it does not exist on this.snapshot
.
Hovering over snapshot
shows type any
:
And throughout the code, anywhere where MyClass.snapshot
is used, the intellisense casts it as any
, so I don;t get any type hints, or errors if I do something incorrect with that object. I'm not sure where to begin debugging this, as my code is a bit more complicated version of the example above. I'm using TS version 4.3.5. Where might I begin debugging this?
CodePudding user response:
As mentioned in the comments, we can use ReturnType
to dynamically acquire the return type of any function. Class members can also be accessed via a type index:
class TimeStep {
snapshot: ReturnType<TimeStep["toJSON"]>;
...
toJSON() {
return {}; // implementation
}
}
I don't know why your environment was not able to do this automatically, but the resultant type checking is the same either way. This is perhaps even a little more descriptive.