This video is available to students only

Union, Literals and Custom Types

In this lesson, we're going to add lite server to our project

Some more types#

Union types#

I hope by now, you understand all the primary data types that TypeScript supports. It comes with extra features and one of them is the Union type. Let's create a new file and call it ts-features.ts. So what is a union type? In the last lesson, I told you how using the any type can be a bad idea. You can actually use the Union type if you're not sure about the data type of the variable.

Let's create a variable called union and give it a value, 5. Let's assign the type, number, and try to change the value to a string; it gives us an error. Here, we can use the union type by including a pipe (|) and adding another type which is a string. You see, the error is gone. There is no limit to how many union types you can use. Let's mutate the variable once again, this time, to a boolean. Let's add another union boolean to our variable and the error's gone.

This is very easy to understand. Although it's always good to know the variable's data type, but if you're not sure, you can use the union type. I use this a lot when I know the variable will store the API request data. I can use union type and type define it as a promise of string or undefined, because if the request fails, your variable will be undefined.

Literal types#

Now, let's talk about the literal types. Usually, we give data types to variables, and as you know, TypeScript infers the data types. Let's create a const, num, and give it a value, 5.4; if we hover over it, it has not just inferred the type number but the value, 5.4, as well. Because it's a const, TypeScript knows that the value is never going to change, so, it infers the value. It's same as giving it a type of value 5.4; see? it doesn't complain. If it were var or let, TypeScript won't infer the value but the data type. But if you explicitly define the value to a variable, it will behave the exact same way. Let's make let x to be hello and give it a type hello as well. Although it's a let, it won't let you change the value to anything else but hello.

Start a new discussion. All notification go to the author.