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

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

function doSomething(obj: Interface1 | interface2 | interface3) { ... }

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;
}

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 ....
}

That's it :)

Now we can do specific operations by checking object interface

Top comments (0)

DEV

Thank you.

 
Thanks for visiting DEV, we’ve worked really hard to cultivate this great community and would love to have you join us. If you’d like to create an account, you can sign up here.