Type inference in TypeScript. Immutable array of concrete string values

Introduction

Let’s solve a real practical problem that I had to face on my React / TypeScript project.

Task

We have an array of specific string values ​​like this “first”, “second”, “third”, “fourth” and “fifth”. It is necessary to display them on the page, that is, to use them somehow, and also to make sure that this data is strongly typed and TypeScript gives us tooltips when it is used in the code.

Solution

First, put the data in an immutable (readonly) array:

const numberNames = ["first", "second", "third", "fourth", "fifth"] as const
  • We have declared a constant numberNames and assigned it an array of string literals;

  • Design as const used to make an immutable tuple from a given array, where specific string literals are stored as literal types;

  • Storing string literals as literal types means that the TypeScript compiler treats each element in the array as a separate type corresponding to its exact string value. For example, the type of the first element ‘first’ is not just a generic string type (string), but a specific type ‘first’;

  • See for yourself by creating two arrays – one with as const, and the other without. And then hover over a variable and see the difference.

Now let’s create a type based on this array:

type NumberName = typeof numberNames[number]
  • Here we have created a type NumberNamewhose value is the union of the types of string literals from the array;

  • Number indexer [number] Retrieves the combined type of the individual array elements. As a result typeof numberNames[number] represents the combined type of array elements:

"first" | "second" | "third" | "fourth" | "fifth"
  • Why [number]and not, for example [string]? It’s simple – as we know, array elements can be accessed through a numeric index: for example, numberNames[0] => "first";

  • Even if we had an array with values ​​of other types, for example [1, ‘blabla’, 555]then in any case we would use [number] in order to create a union type based on it 1 | 'blabla' | 555;

  • By the way, this ability to extract a type from a tuple using an indexer [number]as in our example, appeared in TypeScript 4.1.

Conclusion

What is all this for – to strongly type this list of strings and when we work with it, to receive such hints:

I chose Type inference and as const as the solution because I wanted to make it as flexible as possible with as little code as possible.

PS These are my first steps in the field of writing web articles, and this is accordingly my first article. So I wanted to start with something small to share useful information with all of you. I will be glad to your comments. Thank you!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *