Published on

Defining Types for JSON Object in TypeScript

Authors

Unsurprisingly as the name of the language suggests - TypeScript - you can declare what type elements of the language are. It is basically JavaScript but with types added to variable declarations.

Today I was working on changes to a library and wanted to define the shape and structure for a JSON object. This was to solve an issue where a method was taking any as the type instead of a specific type. This resulted in a runtime error (as opposed to compile-time error) when an empty JSON object {} was mistakenly passed to it:

const doStuff = (aPerson: any): PersonDTO => {
  // ...
}

// ...
const john = {}
const asPerson = doStuff(john)

This was easily fixed by defining an interface for the Person object and changing the type in the function. To define the shape and types of the parameters in this object we define an interface as below:

export interface Person {
  name: string
  surname: string
  age: number
  address: {
    county: string
    province: string
    line1: string
    line2: string
  }
  salary?: number
}

// ...

const doStuff = (aPerson: Person): PersonDTO => {
  // ...
}

// ...
// we now get an error below when trying to lint/compile this
const john = {}
const asPerson = doStuff(john)

What is cool about interfaces in TypeScript is they can be used as they are in languages like Java where you can define the behaviour for a class by defining what methods that class has. But you can also use interfaces to define what JSON objects look like as well as parameters that are optional - those are the parameters with a ? after the name salary? in the above. This is really cool. In languages like Java, you would have to define an interface with getters and setters to enforce the types in a bean which is very boilerplaty. The TypeScript approach is much cleaner and more concise.

It has been a while since I used TypeScript but after having done quite a bit of JavaScript development lately, I really am starting to lean more towards strongly typed languages. Ideally, I like errors to be as obvious as possible. Errors ideally should happen at compile time before the code is even committed. This is as opposed to errors happening at runtime or worse in production at runtime.