Typescript type guards
Created By: chatGPT
Type Guards in TypeScript are special constructs that enable you to determine the type of a variable at runtime. They help in narrowing down the type of a variable within a certain scope, providing better type safety and preventing errors. Below are some commonly used methods of implementing type guards.
// Defining a union type
interface Dog {
bark(): void;
}
interface Cat {
meow(): void;
}
type Animal = Dog | Cat;
One common way to implement a type guard is by using the
typeof
operator. It helps in differentiating between primitive types.function isString(input: any): input is string {
return typeof input === 'string';
}
if (isString(value)) {
console.log(value.toUpperCase()); // Safe to use as a string
}
Another method is to use
instanceof
when dealing with class instances. This can confirm whether an object is an instance of a particular class.class Animal {
// ... class implementation
}
class Cat extends Animal {
meow() { console.log('Meow!'); }
}
function isCat(animal: Animal): animal is Cat {
return animal instanceof Cat;
}
You can also create user-defined type guards using specific properties of an object. This is particularly helpful for interface types.
interface Dog {
bark(): void;
type: 'dog';
}
interface Cat {
meow(): void;
type: 'cat';
}
function isDog(animal: Dog | Cat): animal is Dog {
return animal.type === 'dog';
}
Using these type guards allows for clearer and more maintainable code. They not only enhance type safety, but also provide better autocompletion in your IDE.
const pet: Dog | Cat = getPet();
if (isDog(pet)) {
pet.bark(); // Safe to call bark()
} else {
pet.meow(); // Safe to call meow()
}
By effectively utilizing type guards, you can prevent many potential runtime errors and ensure that your code behaves as expected. Be sure to explore the different methods and choose the one that best fits your scenario.
// Example of a simple type guard usage
const exampleAnimal: Dog | Cat = { meow: () => console.log('Meow!'), type: 'cat' };
if (isCat(exampleAnimal)) {
exampleAnimal.meow();
}