Skip to content

Custom Types

von Schappler edited this page Oct 18, 2024 · 3 revisions

Creating custom types

After having a basic idea on how to properly use basic types on a TypeScript codebase, it's time to have a glance on how to create custom types to be used on your code.

By convention those are created using the type keyword and the name given to type should always start with a capital leterm just like provide in the snippet below.

type CustomType = string;

By doing this, we can use the CustomTypecreated above to declare other variables, like so:

let text: CustomType = 'Some text';

Keep in mind though that creating custom types over basic types can not comy handy, those are more useful when creating "union types" (more about this later) and objects.


Custom types on objects

For the sake of exemplification lets assume that we are working with a person object, fored by 3 properties: name, age and isAdult.

let person1 = {
  name: 'Joe',
  age: 18,
  isAdult: true,
};

The question is, how would we create a type that describes the person object? The anwser to that relies on working with custom types.

To create a custom type for the person object referenced above, we should add the following type definition on our code and then use it when declaring variables that are of the type person:

type Person = {
  name: string;
  age: number;
  isAdult: boolean;
};

let person1: Person = {
  name: 'Joe',
  age: 18,
  isAdult: true,
};

let person2: Person = {
  name: 'Mary',
  age: 18,
  // the line below will trigger a potential error, because the type Person does not expect isadult as a property, but isAdult
  isadult: true,
};

Clone this wiki locally