TypeScript: Only Allow A Property From Interface as Parameter
Photo by Roman Synkevych πΊπ¦ on Unsplash
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.
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.
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 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 π