If you already have a subscription, you can sign in.
Enjoy free content straight from your inbox 💌
00:00
Here we have a type representing a square with a member size and a type rectangle with a member's width and height. Then we have a type shape, which can accommodate both squares and rectangles in our utility function area. In order to discriminate between the square and the rectangle, we check if it has a member size to determine if it's a square, and we check if it has a member width to determine if it's a rectangle. Now, these conditions are not explicitly clear that we are checking if something is a square or a rectangle. We've discussed before how we can improve the situation
00:33
by adding a common member between square and rectangle of different literal types, thus forming a discriminated union. However, if we do not want to modify the types themselves, we can still get the readability benefits by creating user-defined type cards. We start off by copying this condition into a utility function called a square. Notice that this function returns a Boolean value. A user defined type card is simply a function that returns a Boolean value and is annotated in the form. Parameter is type.
01:06
For example, here we have the parameter S shape and the type S squared. Here we are communicating with TypeScript and telling it that if this function returns true, this means that shape is of type square. Now, in terms of type inference, these user defined type cards behave exactly the same as the built-in type cards offered by JavaScript. For example, the in operator. So we can replace the condition in our IF block with a call to our user user-defined type card. And now TypeScript understands that within the block this means the shape must be a square,
01:41
and now we can repeat the process for the rectangle type. Creating a function is rectangle, that is annotated to return shape is rectangle, and then internally simply checks if width is present in the input shape. And now we can replace a property check type card with a much more meaningfully named function call.