DEV Community

Alireza Razinejad
Alireza Razinejad

Posted on

Generic interface check function in TypeScript

There are some situations that we may have several interfaces that object will be described with, like this

const obj: Interface1 | interface2 | interface3
Enter fullscreen mode Exit fullscreen mode

And we have some function that we want to do specific logic for each interface

function doSomething(obj: Interface1 | interface2 | interface3) { ... }
Enter fullscreen mode Exit fullscreen mode

In this situation the first problem will be how check if object have Interface1 or something else, for this goal we need some helper function to do this for us, and what is better than make it generic, so we can have reusable interface check function.

But in this solution we need to pass function specific property that will always be defined inside our object but there is no similar property in other interfaces.

So, our interface check function will be like this

function checkInterface<T>(object: T, uniqueProp: string): object is T {
 return `${uniqueProp}` in object;
}
Enter fullscreen mode Exit fullscreen mode

Okay, now in doSomething function we do this thing safely now

function doSomething(obj: Interface1 | Interface2 | interface3) {
if (checkInterface<interface1>(obj, 'unque_prop')) {
...
} else if ....
}
Enter fullscreen mode Exit fullscreen mode

That's it :)

Now we can do specific operations by checking object interface

Top comments (0)