Literally translated, Type Guard means "type guardian." We often need to create complex types based on backend API responses or programmatic logic operations. Sometimes VS Code throws errors, prompting us to exclude certain uncertain type definitions. While we can use officially defined Utility Types for some operations, more often we need to design these complex type definitions ourselves to narrow types to our desired scope. This is where type guards come in handy.
Type Guard is a runtime check used to narrow the type range of variables.
A Type Guard is a special function that determines whether a variable belongs to a specific type based on certain conditions.
function isNumber(value: any): value is number {
return typeof value === 'number';
}
const someValue: number = 42;
if (isNumber(someValue)) {
console.log(`${someValue} is a number`);
} else {
console.log(`${someValue} is not a number`);
}
Enums are compiled types used to define a set of named constants. They help us express specific value collections more clearly, improving code semantics and readability. Enums can use numbers or strings as enumerated values, and by default, Enum values start from number 0 and auto-increment.
enum Color {
Red = 0,
Green = 1,
Blue = 2,
}
enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT',
}
I encountered a case where I wanted to add enum type guards to implementation logic. Through this approach, we can use fluent semantics to describe our logic.
Suppose we need to handle complex API response data from the backend that may contain multiple types of information. We can combine Enums and Type Guards for type checking to ensure data correctness and consistency.
We have deeply discussed Type Guards and Enums in TypeScript, and explored combining these two powerful tools to improve code safety and maintainability. Type Guards allow us to perform precise type checking at runtime, while enums provide a clear and semantic way to define a set of named constants.
Through practical examples, we demonstrated how to use these techniques when handling complex API response data. Give it a try!