Categories
TypeScript Answers

How to add a class type check in TypeScript?

Spread the love

Sometimes, we want to add a class type check in TypeScript.

In this article, we’ll look at how to add a class type check in TypeScript.

How to add a class type check in TypeScript?

To add a class type check in TypeScript, we can create a function to do the check.

For instance, we write

const isFish = (pet: Fish | Bird): pet is Fish => {
  return (<Fish>pet).swim !== undefined;
};

if (isFish(pet)) {
  pet.swim();
} else {
  pet.fly();
}

to create the isFish function that returns the pet is Fish type.

And we check if pet is a Fish by checking if the swim property isn’t undefined.

Then we call isFish with pet to check if pet is a Fish.

And then we call swim if it is a Fish.

Conclusion

To add a class type check in TypeScript, we can create a function to do the check.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *