DEV Community

Cover image for Typescript: Checking Type of a Value, (interface, type)
SeongKuk Han
SeongKuk Han

Posted on

Typescript: Checking Type of a Value, (interface, type)

Typescript: Checking Type of Value, Interface and Type

Let's say there are animal types and instances of them.

interface Cat {
  catId: number;
}

interface Dog {
  dogId: number;
}

type Bird = {
  birdId: number;
};

const cat: Cat = { catId: 1 };

const dog: Dog = { dogId: 1 };

const bird: Bird = { birdId: 1 };
Enter fullscreen mode Exit fullscreen mode

Then, how do you check the type of the instances?


With typeof

console.log(typeof cat);
Enter fullscreen mode Exit fullscreen mode

Output

object
Enter fullscreen mode Exit fullscreen mode

With instanceof

console.log(cat instanceof Cat);
Enter fullscreen mode Exit fullscreen mode

You would get an error like below.

'Cat' only refers to a type, but is being used as a value here.
Enter fullscreen mode Exit fullscreen mode

In Typescript, for type checking, you can use is operator for type checking.

const isCat = (cat: any): cat is Cat => (cat as Cat).catId !== undefined;
console.log(isCat(cat));
Enter fullscreen mode Exit fullscreen mode

Output

true
Enter fullscreen mode Exit fullscreen mode

As you see, it works well.

In my project, I had to do type checking frequently, so, I made a function using Generic Type to check the type of an instance.

const instanceOf = <T>(value: any, fieldName: string): value is T =>
  fieldName in value;
Enter fullscreen mode Exit fullscreen mode

And you can use the function like this.

const animals = [cat, dog, bird, cat, dog, bird];
console.log(instanceOf<Cat>(cat, "catId"));

const cats = animals.filter((value) => instanceOf<Bird>(value, "birdId"));
console.log("cats", cats);
Enter fullscreen mode Exit fullscreen mode

Output

true
cats [ { birdId: 1 }, { birdId: 1 } ]
Enter fullscreen mode Exit fullscreen mode

I hope it'll be helpful for someone,

Happy Coding!

Top comments (4)

Collapse
 
mrclrchtr profile image
Marcel Richter

To fix typescript errors, you could use:

export const instanceOf = (value: unknown, fieldName: string): value is T => {
if (typeof value === "object" && value !== null) {
return fieldName in value;
}
return false;
};

Collapse
 
lico profile image
SeongKuk Han

Thanks for the solution 👍

Collapse
 
davecdri profile image
davecdri

thank you :)

Collapse
 
lico profile image
SeongKuk Han

You're welcome :)