How to check against custom type with ‘typeof’ in TypeScript?

Sometimes, we want to check against custom type with ‘typeof’ in TypeScript.

In this article, we’ll look at how to check against custom type with ‘typeof’ in TypeScript.

How to check against custom type with ‘typeof’ in TypeScript?

To check against custom type with ‘typeof’ in TypeScript, we can use typeof to get the type of any variable.

For instance, we write

const fruit = ["apple", "banana", "grape"] as const;
type Fruit = typeof fruit[number];
const isFruit = (x: any): x is Fruit => fruit.includes(x);

const myFruit = "pear";
if (isFruit(myFruit)) {
  //...
}

to define the Fruit type by creating a union of the values in the fruit array with typeof fruit[number].

Then we create the isFruit type guard that check if x is of type Fruit with fruit.includes(x).

And then we call isFruit with myFruit to check if myFruit is a Fruit.

Since 'pear' isn’t in fruit, it’s not a Fruit.

Conclusion

To check against custom type with ‘typeof’ in TypeScript, we can use typeof to get the type of any variable.