Typescript literal types
Created By: chatGPT
TypeScript provides a powerful feature called literal types that allow developers to specify exact values a variable can hold. This enhances type safety and allows for more precise type checking. Literal types can be created from strings, numbers, or booleans. Here’s an overview of how to work with them:
String literal types are used when you want a variable to only accept specific string values. For example, you might define a type for the days of the week:
type Day = 'Monday' | 'Tuesday' | 'Wednesday' | 'Thursday' | 'Friday' | 'Saturday' | 'Sunday';
You can then use the Day type in a function:
function isWeekend(day: Day): boolean {
return day === 'Saturday' || day === 'Sunday';
}
Number literal types work similarly. You can restrict a number variable to specific values:
type ZeroToTen = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
Using number literal types in a function:
function isEven(num: ZeroToTen): boolean {
return num % 2 === 0;
}
Boolean literal types also exist and can be useful in creating a more specific type. For instance:
type YesNo = true | false;
You can define a function that uses boolean literals:
function respond(value: YesNo): string {
return value ? 'Yes' : 'No';
}
Literal types can also be used with enums for more complex structures. Enums provide a way to define a set of named constants. Here's an example of combining enums with literal types:
In conclusion, literal types in TypeScript allow for greater precision and type safety in your code. By restricting variable values to specific options, your codebase becomes more robust and easier to maintain.enum Color {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE'
}
type ColorType = Color.Red | Color.Green | Color.Blue;