I am experimenting with TypeScript in the playground and found that it allows me to assign the object returned by JSON.parse()
to a class, even though the object won’t have any methods, and this causes a runtime error. This is surprising to me as my understanding was that TypeScript is typesafe as long as you don’t use as
or any
.
Is it possible to have the type system catch this case, using only type annotations, not changing the behaviour of the code?
class Foo {
inner: Number;
constructor(inner: Number) {
this.inner = inner;
}
getInner() {
return this.inner;
}
}
let result: Foo = JSON.parse('{ "inner": 5 }');
console.log(result.getInner());
1