- Published on
TypeScript Type Checks only Happen at Compile Time
- Authors
- Name
- Yair Mark
- @yairmark
Today I was dealing with a bug on our TypeScript frontend where for some reason the value on the one object was consistently undefined
. This value was being populated from the results of a web service call.
Generally when this happens it is because the key on the JSON object you are mapping from does not have a value mapped to a key with that name. For example person.salary
returns undefined if the object person looks like this (note how the salary
field is missing):
interface Person {
age: number
name: string
surname: string
}
It turns out the server object's properpty name was changed and no error was thrown as this was being parsed on the front end at runtime - TypeScript compiles to JS and does not check anything at runtime.
Unfortunately runtime checks are not a part of the language. Other transpiled languages like Kotlin compile in checks for situations like this. Instead for TypeScript you have to use one of or a combination of the following approaches:
type guard. This is basically a method you code to check types at runtime. You need to define this yourself which can become cumbersome the more types you check.
use a JSON schema to validate types. You define the structure of the object as a JSON schema and validate objects against that.