Currently, I am developing a class where the constructor calls one of its methods toJSON
and sets 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)
}
}
I anticipate that the structure of the return value from toJSON
may change during development. Therefore, I prefer not to hardcode a return type. Even though TypeScript should automatically infer a return type and enforce it, in the current scenario, accessing this.snapshot.nope
will result in an error because nope
does not exist on the inferred return type of toJSON
, hence causing an issue with this.snapshot
. The TypeScript playground demonstrates the expected behavior.
In my codebase, however, the return type never gets correctly assigned to snapshot
— it continues to remain as type any
. Due to the complexity of the code, reproducing the issue can be quite challenging. When inspecting through intellisense, here is what I observe:
Hovering over toJSON
displays the correct inferred type:
https://i.sstatic.net/hpfq2l.png
Hovering over snapshot
reveals the type as any
:
https://i.sstatic.net/RB8Mbl.png
Moreover, within the code, every reference to MyClass.snapshot
casts it as any
, thereby missing out on any type hints or errors when operating with that object incorrectly. Debugging this issue seems overwhelming, considering my codebase is more intricate than the provided example. I'm using TypeScript version 4.3.5. Where would you recommend starting the debugging process?