TypeScript: Only Allow A Property From Interface as Parameter

Dev By RayRay
Β·Apr 20, 2022Β·

2 min read

TypeScript: Only Allow A Property From Interface as Parameter

Photo by Roman Synkevych πŸ‡ΊπŸ‡¦ on Unsplash

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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

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

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.png After 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 😁

Did you find this article valuable?

Support Dev By RayRay by becoming a sponsor. Any amount is appreciated!

See recent sponsors |Β Learn more about Hashnode Sponsors
Β 
Share this