Categories
TypeScript Answers

How to use the is keyword do in TypeScript?

Spread the love

Sometimes, we want to use the is keyword do in TypeScript.

In this article, we’ll look at how to use the is keyword do in TypeScript.

How to use the is keyword do in TypeScript?

To use the is keyword do in TypeScript, we can use it in the return type for type guard functions.

For instance, we write

const isString = (test: any): test is string => {
  return typeof test === "string";
};

const example = (foo: any) => {
  if (isString(foo)) {
    console.log(foo.length);
  }
};
example("hello world");

to create the isString type guard function that check whether test is a string.

test is string is the returned type and it’s true if test is a string and false otherwise.

In example, we call isString with foo to check if foo is a string.

If it returns true, then we can use string properties like length safely.

Conclusion

To use the is keyword do in TypeScript, we can use it in the return type for type guard functions.

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 *