Essential Types And Notations 20 exercises

Creating `type` Aliases

The type keyword allows us to allows us to reference a type by a different name. This is useful when we want to consolidate multiple types into a single type alias.

Creating a Rectangle type with width and height properties looks like this:

type Rectangle = {
width: number;

Loading solution


00:00 So for this solution, we're going to use the type keyword and we're going to say type rectangle equals width height or width number height number there.

00:10 So we can now, instead of having just width number and height number here, we can reference rectangle instead and it will basically use that as an alias for the type. So this is a type alias. That's what we're doing here. And type aliases can contain any types. So it could be a string, could be a number, could be a boolean, could be all sorts of different stuff.

00:31 And now we've still got this one sort of hanging around here. So why don't we refactor this away and turn it into a rectangle instead? And now we've got width number, height number working for both of these and all of our types are doing exactly what we expect them to.

00:46 Now, even if we hover over get rectangle area, you can see that rectangle is being typed as rectangle here. So it's actually sort of a lot cleaner to read too. So often what you'll find is if your types grow really, really big, you want to refactor them out into different spots. We can even put this rectangle type in a different file completely.

01:06 So we can have it in type keyword solution 3, so in a different file here, and then just import it in. So often what you'll find is people have just, let's say they're building a feature, they have lots of files co-located together and they're all using some shared types. They'll put those types in a shared file and import them in.

01:21 So this is a really, really common use case and it's super nice to have the type keyword to be able to kind of have single sources of truth for lots of these types.