Published on

Optional Types And Required In TypeScript

Authors

In TypeScript, you can define an interface that looks like the following:

interface Person {
  name?: string
  surname?: string
}

Generally it is preferable to not have to deal with optional types as you now have to check that the type is not null i.e. present.

There are various reasons you would define an interface this way nonetheless for example if you are receiving a response from a web service you have no control over and through have bad documentation. Or you are dealing with a db model that has nullable fields.

With the above interface if I passed person to a function I would now have to check if name and surname are present:

function hi(person: Person): string {
  if (person.name == null) {
    throw Error('The name field is missing')
  }
  if (person.surname == null) {
    throw Error('The surname field is missing')
  }

  ;`Hi ${person.name} ${person.surname}`
}

But chances are I have already checked and sanitized this object if it came from another service, so I do not want to have to check it again and I do not want to have to map it to another type. In this case TypeScript has a helper type called Required<T> which I can use to basically say "I know none of the values in this interface are null or missing" :

function hi(person: Required<Person>): string {
  ;`Hi ${person.name} ${person.surname}`
}

There are other helper types which can be found here.