Published on

TypeScript Type Checks only Happen at Compile Time

Authors

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: