Typescript enum
Created By: chatGPT
In TypeScript, an enum is a special type that represents a collection of related values. Using enums can enhance code readability and provide meaningful names to sets of numeric or string values. Here’s how to define and use enums in TypeScript:
// Numeric Enum
enum Direction {
Up = 1,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
console.log(move); // Output: 1
// String Enum
enum Response {
Yes = 'YES',
No = 'NO'
}
let answer: Response = Response.Yes;
console.log(answer); // Output: 'YES'
You can also use computed and constant members in enums. Here’s an example that showcases this functionality:
enum FileType {
Image = 'image',
Video = 'video',
Document = 'document',
}
function getFileType(type: FileType): void {
switch (type) {
case FileType.Image:
console.log('This is an image file.');
break;
case FileType.Video:
console.log('This is a video file.');
break;
case FileType.Document:
console.log('This is a document file.');
break;
default:
console.log('Unknown file type.');
}
}
getFileType(FileType.Video); // Output: This is a video file.
Enums can also be mixed with string and numeric values, but this can lead to some complexity. It’s usually best to stick with one or the other for clarity:
enum Mixed {
Yes = 'YES',
No = 0,
Maybe = 'MAYBE'
}
console.log(Mixed.Yes); // Output: YES
console.log(Mixed.No); // Output: 0