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 };
Then, how do you check the type of the instances?
With typeof
console.log(typeof cat);
Output
object
With instanceof
console.log(cat instanceof Cat);
You would get an error like below.
'Cat' only refers to a type, but is being used as a value here.
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));
Output
true
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;
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);
Output
true
cats [ { birdId: 1 }, { birdId: 1 } ]
I hope it'll be helpful for someone,
Happy Coding!
Top comments (4)
To fix typescript errors, you could use:
Thanks for the solution 👍
thank you :)
You're welcome :)