If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
The most common use case of type definitions in TypeScript is to declare the structure of an object. For example, here we have a type representing a point in two dimensional space with two members, X and Y of type number. Now we can create a new type to represent a point in three dimensional space using an intersection type, bringing in all of 0.2 D and adding the member Z of type number. Now of course there are various reasons to use the type definition. For example, we can enforce the structure of a variable in our code base, and now if you make any type errors, for example, forget
00:34
to assign the Z member, we get a nice compile time error from TypeScript. Now, in addition to type aliases, which are created using the type keyword, the same can be achieved in TypeScript using interfaces which are created with the interface keyword beyond the keywords type versus interface. The other key syntactic difference is the use of the assignment operator in a type alias. This is because type aliases are simply a way to give names to any possible type annotation syntactically, similar to
01:07
how you would assign a value to a variable. In JavaScript interfaces, however, operate on body blocks syntactically, similar to how you would create a class in JavaScript. Now for creating 0.3 D in type aliases, we used an intersection type to bring in all of 0.2 D and then add the member Z. We can achieve the same effect with TypeScript interfaces by using the extent keyword, similar to how you would do it in a JavaScript class. Now, in terms of usages, the type alias and the interface can be used in a similar fashion. For example, we can use the interface to declare a variable
01:42
of a particular type, just like we did for the type alias, and this provides the same level of safety that we were getting from the type alias. For example, if you forget to provide the member Z, we get a nice compile time error from TypeScript. Now, just like type aliases interfaces in TypeScript only exist for compile time type checking and are not a part of the output JavaScript generated by the compiler. There are two key reasons why interfaces exist in TypeScript. One reason is familiarity For developers coming from other programming languages.
02:15
For example, they get to use the extend keyboard and can create type hierarchies with a more familiar syntax. The other key reason is interface declaration merging, and we will look at that in the next lesson.