Exploring TypeScript’s Literal Types
Exploring TypeScript's Literal Types
TypeScript is an increasingly popular open-source programming language that provides a unified type system and powerful type-checking capabilities. One of the features that set TypeScript apart from other languages is its support for literal types. In this article, we’ll be taking a closer look at how to use literal types in TypeScript.
What are Literal Types?
Literal types are predefined constants that represent a specific value. For example, if you have a variable that only accepts numbers that are divisible by 3, you could define it as:
let x: 3 = 3;
This would restrict the variable to only accept values that are divisible by 3 (i.e., 3, 6, 9, 12, etc.).
Using Literal Types with Union Types
In addition to being used on their own, literal types can also be combined with union types to create more complex data types. For example, let’s say we want to create a variable that only accepts values of either “red”, “green”, or “blue”. We could do this using the following syntax:
let y: “red” | “green” | “blue”;
Here, we’re using the union type operator (|) to specify that the variable can accept one of the specified literal types.
Creating Custom Literal Types
In TypeScript, it’s also possible to create custom literal types. For example, if we wanted to create a type that only accepted strings that contained either the word “hello” or “world”, we could do so using the following syntax:
type HelloWorldString = “hello” | “world”;
let z: HelloWorldString = “hello”; // valid
let a: HelloWorldString = “foo”; // invalid
Here, we’re using the type keyword to create a new type called HelloWorldString, which is then used to define the variable z. As you can see, the variable is restricted to only accept strings that contain either the word “hello” or “world”.
Conclusion
Literal types are an incredibly powerful feature of TypeScript that enable developers to create highly precise data types. In this article, we’ve taken a look at how to use literal types on their own, combine them with union types to create more complex data types, and create custom literal types. By understanding how to use these types, you can enhance your TypeScript code with greater type safety and more precise data types.