Use Self-Made Type Guard with TypeScript "is" Operator
Tags: typescript, programming, node, tutorial
Published: 2024-05-30 14:00:00

## Introduction

Hello, I'm haruhikonyan and I've been working on WESEEK for a while now.
Do you use TypeScript?
You can write not only front-end code, but also server-side code with Node, and it's also type-safe!
In this article, I want to introduce a self-made type guard using the "is" operator, one of the user-defined type guards, to make TypeScript more robust and useful.

---

## What is a Type Guard?

First of all, what is a type guard?
You can read the [reference](https://basarat.gitbook.io/typescript/type-system/typeguard) for an overview, but the one you will probably use the most is as follows.

![Type Guard](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t3lw5xt0t2zf3zpr8u8f.png)

We often use null and undefined checks as you can see. Of course, it is often necessary to determine not only primitive types such as null, but also original types defined by the user.

This is where the "is" operator comes in.

## What is "is"?

It is probably faster to look at than explain it so I will show you an example first.
[Axios](https://github.com/axios/axios#), one of the most widely used libraries, has a simple implementation called `isAxiosError`.

As you can see in the [example](https://github.com/axios/axios#typescript), it determines whether a variable is an AxiosError or not, and type guarding is used to narrow down the variable type.

I was going to introduce it as it is, but the original code was in JavaScript, so I rewrote it here in TypeScript to make it relatively easy to read.

![is](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ab4467alfnknlv59r2iv.png)

### isObject

This is also like a real type guard. Since the "is" operator is not used, it does not narrow down the type of the type guard in a transpiler sense, but it guarantees that the type is not null and is of type object with the `typeof`.

### isAxiosError
Here is the main issue. First, let's look at what's inside.

![isAxiosError1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3v7eht5jw9oef53pl3b6.png)

and the first thing is that `payload` is an object. This is good.
Then we see that the property of that `payload` has the value `isAxiosError` `true`.
That is all.
It seems that the error object issued by Axios always contains the value `true`.

![isAxiosError2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ymyirwmpgn411l05yeta.png)

This means that if the function `isAxiosError` returns `true`, it will tell the TypeScript transpiler that the `payload` given as an argument is (is) type `AxiosError<T, D>`.

## More Explanation

The above is almost all that has been explained, but the following URL contains more detailed and complete specifications, so if you are in doubt or want to know more, check it out.

- https://basarat.gitbook.io/typescript/type-system/typeguard
- https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates

---

## Made a Function to Determine the String Array

I hope everyone now understands the “is” operator.
Here, I would like to introduce a function I created when I was using TypeScript and wanted to know exactly whether a certain variable was a string array or not.

### Function created

![Function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ttxnutyhzt5y5gj450s.png)

If you have read the above explanation, you may understand it. The explanation is that what we receive as `value` is an array with `isArray`, and if the `value` is determined to be an array, the `every` function tells the transpiler that it is of type `string[]` if all of its elements are of type `string`.

In practice, when a query is received from a Request in `express`, the type of query is `string | string[] | QueryString.ParsedQs | QueryString.ParsedQs[] | undefined`, a type that considers all possibilities. 

If you want just a `string`, you can use `typeof`, but if you want to determine `string[]`, `isArray` is not enough, so I created my type guard.

## Be Careful not Falsify the Mold

I'm sure that you have been tempted to try your hand at type determination using the "is" operator. However, if you write `is Hoge` in the definition and the function returns even true, the transpiler already knows that it is a Hoge type, so if you write a proper judgment, it will be a false type.

The `isAxiosError` is not always appropriate, but if an appropriate object has a property called `isAxiosError` and true is set there, it is assumed to be of type `AxiosError`. Both function definition and use of the function should be aware of this danger.

Let's create a more type-safe and robust system, without escaping to “as” or “any”!

---

## About Us💡
In addition, I want to introduce a little more about GROWI, an open software developed by us **WESEEK, Inc**.

**GROWI** is a wiki service with features-rich support for efficient information storage within the company. It also boasts high security and various authentication methods are available to simplify authentication management, including **LDAP/OAuth/SAML**.

**GROWI** originated in Japan and GROWI OSS is **FREE** for anyone to [download](https://docs.growi.org/en/admin-guide/?utm_source=dev+community&utm_medium=referral&utm_campaign=Use_Self-Made_Type_Guard_with_TypeScript_is_Operator) and use **in English**.

For more information, go to [GROWI.org](https://growi.org/en/?utm_source=dev+community&utm_medium=referral&utm_campaign=Use_Self-Made_Type_Guard_with_TypeScript_is_Operator) to learn more about us. You can also follow our [Facebook](https://www.facebook.com/people/GROWIcloud/100089272547238/) to see updates about our service.

![GROWI.org](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rhpa0qcdukeall2vfsj.png)