Is there a difference between me saying the following:
interface/class MyRecord {
...
}
const record: MyRecord = { ... }
vs
const record: MyRecord = JSON.parse('{...}') as MyRecord?
Is there a difference between me saying the following:
interface/class MyRecord {
...
}
const record: MyRecord = { ... }
vs
const record: MyRecord = JSON.parse('{...}') as MyRecord?
2
Answers
In the first example TypeScript will check the object literal conforms to the specified type and error if you make a mistake there. In the second example, the JSON isn’t parsed until runtime. The
as
statement lets you assert that result will be of that type but TypeScript can’t help you ensure you are correct.JSON also limits you to the data types supported by JSON.
Generating a string and then passing it through the JSON parser is likely to be less efficient than just using an object literal.
Yes, the second approach doesn’t have the same level of type safety as the first one. In the first approach, you will get a TypeScript error if the object literal doesn’t match the shape defined by the interface or class. Conversely, by using the
as
keyword, you are "pretending" that it will be the same type, hence, TypeScript will not check for shape matching.