Web Development
2m ago
706

How to Extract The Indexes of Any Array in TypeScript

With a Full Explanation and Potential Use Cases

How to Extract The Indexes of Any Array in TypeScript
This image has been generated by AI.

So I came across this tweet from Matt Pocock on X and it's very exciting.

However, Matt doesn't explain this trick in detail.

He also doesn't suggest any potential use cases for this trick which is a bummer.

I see this as a missed opportunity for Matt, and therefore I believe it is my duty to explain this trick to level up your TypeScript abilities!

So without further ado… Let’s dive right in!


ToNumber Type

The purpose of the ToNumber type is to take in a key that resembles an array index, then parse it into a number. E.g. "42" -> 42 as a number.

Here is the code for ToNumber with an explanation down below:

  • Key extends PropertyKey ensures the input will extend the built-in PropertyKey type, which equals string | number | symbol
  • We check if the input Key can be transformed into a template literal that infers Index as a number.
  • In simpler terms, we perform a conditional to check that the input type can be parsed into a number.
  • If true, the type returned is a number (Index).
  • If false, the type is never.

IndexesOfArray Type

The purpose of this type is simple.

  1. Take in the type of a readonly Array.
  2. Parse every index in this Array to a number.
  • The generic Array type can be of any type, as long as it's readonly.
  • ToNumber uses the keyof operator to extract each index from the input Array and parse it into a number.

Usage Example

In this example, we create a simple array of names and mark it as const.

This is very important so we ensure the array is readonly.

Lastly, we pass in the type of the array names and use IndexesOfArray to extract the number indexes.

If you hover over the resulting NameIndexes type, you should expect the following type:

Conclusion

That's about it!

This is a cool little trick that you can use in your TypeScript applications.

I personally don't see any real use case for this, however it's a very cool trick regardless.

If you have a use case for this, please let us know in the comments down below!


If you enjoyed this article, please make sure to Subscribe, Clap, Comment and Connect with me today! 🌐

References