I am experimenting with typescript in the typescript 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 typescript type system catch this case, using only type annotations, not changing the behaviour of the code?
<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());
</code>
<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());
</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());