DEV Community

Cover image for TypeScript Tutorial For Beginners: The Missing Guide - Part 4
Valentino Gagliardi
Valentino Gagliardi

Posted on • Originally published at dev.to

TypeScript Tutorial For Beginners: The Missing Guide - Part 4

Just crossed 5k follower on dev.to! Thank you everyone! What a fantastic community! Who's on Twitter too? Let's connect => I'm here.

What is TypeScript and why you may want to use it? Learn more with this TypeScript tutorial for beginners and start adding types to your JavaScript code!

Originally published on valentinog.com/blog

In this episode:

  • type aliases vs interfaces
  • more on interfaces
  • conclusions and resources

TypeScript tutorial for beginners: type aliases vs interfaces

So far we've seen the interface as a tool for describing objects and custom types. But lurking through other's people code you might also have noticed the keyword type.

Apparently interface and type are used interchangeably in TypeScript, but they're different in many ways. And that's cause of confusion for TypeScript beginners.

Remember: an interface in TypeScript is the shape of something, most of the times a complex object.

A type on the other hand might also be used to describe a custom shape, but it's just an alias, or put it another way, a label for a custom type. For example, let's imagine an interface with a couple of fields, one of them being a union type of boolean, number, and string:

interface IExample {
  authenticated: boolean | number | string;
  name: string;
}
Enter fullscreen mode Exit fullscreen mode

With a type alias you can extract that custom union type for example, and create a label named Authenticated:

type Authenticated = boolean | number | string;

interface IExample {
  authenticated: Authenticated;
  name: string;
}
Enter fullscreen mode Exit fullscreen mode

This way you can isolate what changes, so you don't have to copy/paste the union type all over the codebase.

If you want to apply type to our example (filterByTerm) create a new label named ILinks and assign Array to it. That way you can reference the former instead of the longer scheme:

// the new label
type ILinks = Array<ILink>;
// the new label

function filterByTerm(
  input: ILinks,
  searchTerm: string,
  lookupKey: string = "url"
): ILinks {
  if (!searchTerm) throw Error("searchTerm cannot be empty");
  if (!input.length) throw Error("input cannot be empty");
  const regex = new RegExp(searchTerm, "i");
  return input.filter(function(arrayElement) {
    return arrayElement[lookupKey].match(regex);
  });
}

const obj1: ILink = { url: "string1" };
const obj2: ILink = { url: "string2" };
const obj3: ILink = { url: "string3" };

const arrOfLinks: ILinks = [obj1, obj2, obj3];

filterByTerm(arrOfLinks, "string3");
Enter fullscreen mode Exit fullscreen mode

Now, that's not the most clever example of labelling types but you should get the point. So what to use between interface and type? I prefer interface for complex objects. An approach suggested by the TypeScript doc as well:

Because an ideal property of software is being open to extension, you should always use an interface over a type alias if possible.

Hope it helped to clarify your doubts.

In the next section we'll take a quick look at two more TypeScript topics before saying goodbye. Keep going!

TypeScript tutorial for beginners: more on interfaces and objects

Functions are first class citizens in JavaScript, yet Object is the most important entity in the language.

Objects are mostly containers for key/value pairs and it should be no surprise to you that they can also hold functions. When a function lives inside an object it has access to the "host" object through the keyword this:

const tom = {
  name: "Tom",
  city: "Munich",
  age: 33,
  printDetails: function() {
    console.log(`${this.name} - ${this.city}`);
  }
};
Enter fullscreen mode Exit fullscreen mode

If you need a refresher on "this" check out This in JavaScript from The Little JavaScript Book.

So far you saw TypeScript interfaces applied to simple objects for describing strings and numbers. But they can do a lot more. Let's make an example. Create a new file named interfaces-functions.ts with the following code:

const tom = {
  name: "Tom",
  city: "Munich",
  age: 33,
  printDetails: function() {
    console.log(`${this.name} - ${this.city}`);
  }
};
Enter fullscreen mode Exit fullscreen mode

It's a JavaScript object but it needs types. Let's make an interface to make tom conforming to a well defined shape. How about "IPerson"? And while there let's also apply the new interface to tom:

interface IPerson {
  name: string;
  city: string;
  age: number;
}

const tom: IPerson = {
  name: "Tom",
  city: "Munich",
  age: 33,
  printDetails: function() {
    console.log(`${this.name} - ${this.city}`);
  }
};
Enter fullscreen mode Exit fullscreen mode

Compile the code (npm run tsc) and watch it fail:

interfaces-functions.ts:11:3 - error TS2322: Type '{ name: string; city: string; age: number; printDetails: () => void; }' is not assignable to type 'IPerson'.
  Object literal may only specify known properties, and 'printDetails' does not exist in type 'IPerson'.
Enter fullscreen mode Exit fullscreen mode

Cool, IPerson does not have any property named printDetails but more important it should be a function. Luckily TypeScript interfaces can also describe functions. Here's how:

interface IPerson {
  name: string;
  city: string;
  age: number;
  printDetails(): void;
}
Enter fullscreen mode Exit fullscreen mode

Here we added a property printDetails of type function, returning void. void is useful as a return value for functions that ... don't return anything at all.

A function that prints to console in fact does not return anything. If we were to return a string from printDetails we could adjust the return type to string:

interface IPerson {
  name: string;
  city: string;
  age: number;
  printDetails(): string;
}

const tom: IPerson = {
  name: "Tom",
  city: "Munich",
  age: 33,
  printDetails: function() {
    return `${this.name} - ${this.city}`;
  }
};
Enter fullscreen mode Exit fullscreen mode

Now, what if the function has parameters? In the interface you can add type annotations for them:

interface IPerson {
  name: string;
  city: string;
  age: number;
  printDetails(): string;
  anotherFunc(a: number, b: number): number;
}
Enter fullscreen mode Exit fullscreen mode

and if you start typing "an..." inside an object implementing IPerson, most IDE will auto complete the function for you. Developer productivity at its finest.

What's missing from this guide?

For obvious reasons I couldn't cover every single TypeScript feature here. For example I intentionally left off ES2015 classes and their relation with interfaces or more advanced types like Partial.

It's possible I'll cover more TypeScript on future posts but if you're in a hurry head over the TypeScript doc. The official TypeScript documentation is not so friendly but it should be easier for you to dig deeper into it after reading my guide.

Conclusions and resources

What a journey! Thanks for reading and great job on following the guide, I hope you're now ready to use TypeScript in your projects! Feel free to come back here or bookmark the page if you need an handy guide to TypeScript.

In this TypeScript tutorial you learned:

  • type annotations for variables, function parameters, and return values
  • interfaces
  • custom types
  • type aliases

You've seen TypeScript saving my JavaScript code from silly errors, ranging from wrong argument types to malformed return values. It bears repeating that TypeScript is not a replacement for testing. It is indeed a valuable tool, hard to grasp at first but totally worth the investment (like my old friend Redux).

If you want to stay updated on TypeScript's evolution I suggest following a couple of blogs:

The official TypeScript blog where you can learn about the new releases and features.

The blog of Marius Schulz, a software engineer passionate about all the things TypeScript. He also runs a TypeScript weekly newsletter.

After reading my TypeScript tutorial you can also continue exploring the language with the TypeScript book, a fantastic, free resource.

Thanks again for reading and stay tuned!

Top comments (0)