DEV Community

Cover image for TypeScript: Only Allow A Property From Interface as Parameter
Dev By RayRay
Dev By RayRay

Posted on • Originally published at hasnode.byrayray.dev on

TypeScript: Only Allow A Property From Interface as Parameter

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!

divider-byrayray.png

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.

interface Address {
    streetname: string;
    housnumber: number;
    postal: string;
    city: string;
}

Enter fullscreen mode Exit fullscreen mode

divider-byrayray.png

Use keyof operator

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

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

Enter fullscreen mode Exit fullscreen mode

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.

divider-byrayray.png

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)

divider-byrayray.png

Thanks!

hashnode-footer.pngAfter reading this story, I hope you learned something new or are inspired to create something new! 🤗 If so, consider subscribing via email (scroll to the top of this page) or follow me here on Hashnode.

Did you know that you can create a Developer blog like this one, yourself? It's entirely for free. 👍💰🎉🥳🔥

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 😁

Top comments (0)