• 1 min

TypeScript: Only Allow A Property From Interface as Parameter

TypeScript: Only Allow A Property From Interface as Parameter
Table of Content

So lately I was working with a team member on an Angular Pipe. We had an Address Interface and wanted to only allow an argument that was property from the Adress Interface. But how do you define that?

It turns out very simple, we need to use the keyof operator!

Interface

First, we have to check the Address interface. Below is a more simplified version of what we use, but this is perfect for this example.

adress.interface.tsts
interface Address {    streetname: string    housnumber: number    postal: string    city: string}

Use keyof operator

With the keyof operator, we can say that a parameter should be equal to the property of an interface.

fake-function.tsts
function fakeFunc(param: keyof Address): void {  console.log(param);}

Now we can ensure that this function is only being used with a parameter that exists in the Address interface. Otherwise, you will get a TypeScript interface.



Validate the function

In the example, you can see that the param ‘streetname’ is accepted, but the parameter ‘random’ is giving the error “Argument of type ‘“random”’ is not assignable to parameter of type ‘keyof Address’.” because it’s not in the interface. (To see the compile error, you need to click the check it on CodeSandbox)


Thanks

After reading this post, I hope you learned something new or are inspired to create something new! 🤗

If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM’s are always open 😁.

RayRay

I’m Ray, a Frontend Developer since 2009 living in the Netherlands. I write about Frontend Development, JavaScript, TypeScript, Angular, CSS, VueJS and a lot more related topics.

Want to reach me for comments or questions on my blog? Send a DM on Twitter @DevByRayRay