Enjoy free content straight from your inbox 💌
00:00
Let's create two TypeScript types. A type user with a member ID of type string and a type product with a member of ID of type string. When we have two variables, one a user and another a product. Now the structure for the user and the product type is exactly the same. That is, they both have a member ID of type screen. TypeScript type system is structural. It does not care about the names of the types. What this means is that the user and the product has the same type compatibility. This means that you can assign a user to a product
00:34
or a product to the user because they have the same structure. Now let's look at another example Here we have two types, a type four, a point in two dimensional space with the members X and Y, and a type four, a point in three dimensional space with the same members as well as an additional member Z of type number. Next, we create two variables, one of type 0.2 D and one of type 0.3 D. An additional feature of the typescripts structural type system is that extra information is okay. What this means is that we can assign a 0.3 D to a 0.2 D
01:09
because a 0.3 D does have the members that are required by 0.2 D, which is X and Y. Now, such an assignment can also happen indirectly. For example, hey, we have a function that expects to be passed in a 0.2 D as an argument. Now because a 0.3 D contains all the information that is required by a 0.2 D, we can actually invoke this function with a 0.3 D without any compile time errors. Now this is also called duck typing. That is if it works like a duck and quacks like a duck, then it must be a duck.
01:42
And a 0.3 D is all the walking talking features of a 0.2 D. Now a 0.2 D on the other hand, does not have all the features that are required by a 0.3 D. Specifically, it is missing the property Z of type number. Therefore, if you try to assign a 0.2 D to a 0.3 D, TypeScript will raise a compile time error. And similarly, if there is a function that expects a 0.3 D and we try to pass in a 0.2 D, we will get a compile time error from TypeScript.