How To Let a TypeScript Function Accept an Index Type as Parameter
A perfect solution for the KeyOf type in TypeScript
If you got the error “Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type” in TypeScript via TSLint or Visual Studio Code? Here is your solution 👍
It sometimes happens that you want to have a generic function to get a specific property from an array of key-value pairs. But how do you type that correctly in TypeScript?
Let’s see this example function. TSLint won’t accept this.
You will get an error like “Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘Vaccination’.”.
The error is given because you can’t guarantee that the dataProp
parameter has a property from the Vaccination
interface. When we keep it a string
type, it will give error's when a property is not found in the Vaccination
interface.
The Vaccination
interface looks like this.
So how can we correctly resolve this error and still use it like item[dataProp]
?
It’s super simple. Just use keyof Vaccination
here. Via the keyof
we can tell that we only accept properties from the Vaccination
interface as a function parameter.
If you want to dive deeper into TypeScript, I highly recommend the story “Mastering TypeScript’s Mapped Types” by Jose Granja .
Conclusion
Learning the basics and advanced types of TypeScript will be very beneficial to prevent error’s in the browser. Do you like TypeScript? Or do you think it’s too much?
Thanks!
I hope you learned something new or are inspired to create something new after reading this story! 🤗 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 😁