Introduction
A real practical problem I had to face and solve in my React/TypeScript project.
Imagine having a list of specific string values, such as "first", "second", "third", "fourth", and "fifth"
. Your goal is to somehow use these values while ensuring strict type checking. This way, TypeScript will provide autocompletion information, making it easier to work with them and improving code reliability.
Solution
First, let's put the data in a readonly array:
const numberNames = ['first', 'second', 'third', 'fourth', 'fifth'] as const
- We've declared the
numberNames
constant and assigned it an array of string literals:['first', 'second', 'third', 'fourth', 'fifth']
; - The
as const
assertion is used to make the array a readonly tuple where the specific string literals are preserved as literal types.
Now, let's make a type off of the array:
type NumberName = typeof numberNames[number]
- Here we've introduced the
NumberName
type alias and assigned it the union typetypeof numberNames[number]
; -
typeof numberNames[number]
refers to the type of the numberNames array, which is the union of the string literal types present in the array; - The number indexer
[number]
extracts the union type of the array's individual elements. As a result,typeof numberNames[number]
represents the combined type of the array's elements.
The Role of Type Inference:
When defined as a constant with as const
, TypeScript infers the exact string literals assigned to numberNames
as the type of each array element. This means that the type of NumberName is 'first' | 'second' | 'third' | 'fourth' | 'fifth'
Conclusion
- I picked Type Inference since I wanted to implement the solution as flexible as possible and with the least amount of code;
- TypeScript's type inference improves code correctness and tooling support by preserving types based on assigned values. We demonstrated how
as const
creates readonly tuples of string literals, and inferred types to create unions. This knowledge will help us write robust and type-safe code.
P.S. I am taking my first steps into the realm of web article writing, and this one is my first ever. So, I wanted to start with a small case to share some useful information with all of you. Your thoughts, comments, and suggestions are most welcome. Thank you!
Top comments (0)