DEV Community

Cover image for Ultimate Guide to Types in Typescript
Johnny Simpson
Johnny Simpson

Posted on • Originally published at fjolt.com

Ultimate Guide to Types in Typescript

Typescript is a strongly typed langauge built on top of Javascript. As such, types have to be defined in Typescript when we write our code, rather than inferred as they normally are in Javascript.

In this guide we'll be diving into how types work in Typescript, and how you can make the most of them. If you're totally new to Typescript, start with our guide on making your first Typescript project.

The Fundamental types in Typescript

Javascript has a number of different types. If you want to learn about how types work in Javascript, read our guide here. In this guide, we'll be covering the main types you can use in Typescript. An understanding of Javascript types will be useful, but for simplicity, below is a list the most fundamental Typescript types you will see the most:

  • undefined - when something is not defined in the code, or does not exist.
  • any - refers to any type - essentially not enforcing a type at all.
  • enum - an enum - see here for more on enums.
  • number - a number between -2^53 - 1 and 2^53 - 1, i.e. 1.
  • string - a combination of characters i.e. test.
  • boolean - true or false.
  • bigint - a number bigger than 253 - 1.
  • symbol - a completely unique identifier.
  • function - self explanatory - a function.
  • object - an object or array
  • never - used in functions - for when a function never returns a value, and only throws an error.
  • void - used in functions - for when a function never returns a value.

Custom Types in Typescript

Typescript also allows us to define our own custom types. You can learn about that here.

Fundamentals of Types in Typescript

Now that we've outlined all the fundamental types that Typescript uses, let's take a look at how they work. First, let's start with syntax basics.

Using Typescript types in Variables

The syntax of types on variables in Typescript is relatively straight forward. If we expect a variable to be of a specific type, we define it after a colon, after the variable name. For example, the below variable is defined as having type number.

let x:number = 5;
Enter fullscreen mode Exit fullscreen mode

Similarly, a string type might look like this:

let x:string = "Some String";
Enter fullscreen mode Exit fullscreen mode

If you do not define the type of a variable properly, Typescript will throw an error. For example, let x:string = 5 would throw the following error:

Type 'number' is not assignable to type 'string'.
Enter fullscreen mode Exit fullscreen mode

Defining Object Types in Typescript

Objects are everywhere in Javascript, and it's no different in Typescript. An object in Typescript is of type object, but values inside an object also have their own types. In the most basic example, we can define a variable as type object, which refers to an object of any length or value set:

let myObject:object = { a: 1 };
Enter fullscreen mode Exit fullscreen mode

If we want to get a little more complicated, we can also define the expected types of properties within an object. Suppose we have an object where we have 3 properties:

  • name, of type string
  • age, of type number
  • interests, of type object, where interests is optional We can define each of these explicitly, using the following format:
let userOne:{ name: string, age: number, interests?: object } = { name: "John Doe", age: 24, interests: [ 'skiing', 'hiking', 'surfboarding' ] };
Enter fullscreen mode Exit fullscreen mode

As you might notice, this is becoming a little messy! Often, when we do this, we'll create custom types. You can learn more about custom types here, but as an example, here is the same code using a custom type instead:

type User = {
  name: string,
  age: number,
  interests?: object
}

let userOne:User = { name: "John Doe", age: 24, interests: [ 'skiing', 'hiking', 'surfboarding' ] };
Enter fullscreen mode Exit fullscreen mode

Now we have a nice clean User type that we can apply to any variable or function. Next, let's look at arrays.

Defining Array Types in Typescript

Since Arrays and Objects can contain their own types within, how we define them is slightly different. For arrays, the most basic way to define the type is to use the type[] syntax. For example, an array of strings looks like this:

let arrayOfStrings:string[] = [ 'some', 'strings' ];
Enter fullscreen mode Exit fullscreen mode

Here, string can be replaced with any other valid type. If we know the exact number and types of elements that will appear in our array, we can define it like this:

let myArray:[ string, number ] = [ "some", 15 ]
Enter fullscreen mode Exit fullscreen mode

In Typescript, when we define an array like this, with fixed types and a fixed length, it is known as a Tuple.

Mixed Array Types in Typescript

Sometimes, an array may be made of multiple types, but have an unknown length. In this situation, we can use a union type. For instance, an array of unknown length which only consists of strings and numbers, looks could be defined as this:

let myArray:(string|number)[] = [ "some", 15 ]
Enter fullscreen mode Exit fullscreen mode

Again, for more complicated types, though, we may want to define our own types. You can learn more about custom types here.

Using Typescript types in Functions

The same principles ultimately apply to functions - the only difference here being that a function also often has a return value. Let's start by looking at a simple example without a return function. Notice that we define the type of each argument in the function:

function generateName(firstName: string, lastName: string) {
  console.log(`Hello ${firstName} ${lastName}`)
}

// Run the function
generateName("John", "Doe");
Enter fullscreen mode Exit fullscreen mode

This function will run successfully, since we've given the right types when we ran the function (i.e. both arguments are strings).

One fundamental difference between Typescript and Javascript, is that if we were to run generateName("John");, Typescript would give us the following error:

Expected 2 arguments, but got 1.
Enter fullscreen mode Exit fullscreen mode

Since Typescript is far more strict than Javascript, it was expecting two arguments - not one. If we want this to work, we have to explicitly tell Typescript that argument two is optional. We can do this by adding a ? after the second argument. As such, the following code works fine, with no errors:

function generateName(firstName: string, lastName?: string) {
  console.log(`Hello ${firstName} ${lastName}`)
}
// Run the function
generateName("John");
Enter fullscreen mode Exit fullscreen mode

Using Typescript in Functions with Return Types

Adding a return type in Typescript is straightforward. If a function returns something using the keyword return, we can enforce what type the data from return should be. Since we are returning nothing - so our return type is known as void.

If we want to add our return type to this function, we use the same :, so our code looks like this:

// Note that we have added : void!
function generateName(firstName: string, lastName: string): void {
  console.log(`Hello ${firstName} ${lastName}`)
}
// Run the function
generateName("John", "Doe");
Enter fullscreen mode Exit fullscreen mode

Now Typescript knows that this function will only ever return nothing. If it starts to return something, typescript will throw an error:

Type 'string' is not assignable to type 'void'.
Enter fullscreen mode Exit fullscreen mode

As such, Typescript helps protect us from unknown pieces of code trying to return data in functions. Let's suppose we want to change our function to return, rather than console.log. Since our return will be of type string, we simply change our function's return type to string:

function generateName(firstName: string, lastName: string): string {
  return `Hello ${firstName} ${lastName}`;
}
// Run the function
let firstUser = generateName("John", "Doe");
Enter fullscreen mode Exit fullscreen mode

Writing functions as variables in Typescript

Javascript has a common notation where functions are written as variables. In Typescript, we can do the same, we just have to define the types up front. If we wanted to convert our function above to the variable format, it would look like this:

let generateName:(firstName: string, lastName: string) => string = function(firstName, lastName) {
  return `Hello ${firstName} ${lastName}`;
}
Enter fullscreen mode Exit fullscreen mode

Notice one small difference here, is that the return type is after =>, rather than :. Also note, that we did not define types for firstName or lastName in the function() itself - this is because we defined them as part of the variable - so no need to do so again.

Conclusion

After this, you should have a good understanding of how types work in Typescript. In this article, we have covered:

  • The fundamental and most common Typescript types
  • How to define variable and function types in Typescript
  • How to set the return type of a function in Typescript
  • Creating basic custom types for objects in Typescript
  • How to create array and tuple types in Typescript

I hope you've enjoyed this introduction to Typescript types. You can find more Typescript content here.

Top comments (0)