How To Let a TypeScript Function Accept an Index Type as Parameter

A perfect solution for the KeyOf type in TypeScript

Dev By RayRay
·Aug 3, 2021·

2 min read

How To Let a TypeScript Function Accept an Index Type as Parameter

Subscribe to my newsletter and never miss my upcoming articles

Play this article

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!

hashnode-footer.png 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 😁

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

Impressum

I learn by writing, and write while learning more and more each day!👊 A developer is never finished with learning, thinking that is the most stupid thing to do 🤣