Introduction
Loops play a pivotal role in programming, enabling code execution without redundancy. JavaScript developers might be familiar with foreach
or do...while
loops, but TypeScript offers its own unique looping capabilities at the type level. This blog post delves into three advanced TypeScript looping techniques, demonstrating their importance and utility.
Mapped Types
Mapped Types in TypeScript allow transformation of object properties. Consider an object requiring immutable properties:
type User = {
id: string,
email: string,
age: number
};
To create an immutable version of this type, we traditionally hardcode it. However, to maintain adaptability with the original type, Mapped Types come into play. They use generics to map each property, offering flexibility to modify property characteristics. For instance:
type ReadonlyUser<T> = {
readonly [P in keyof T]: T[P];
};
This technique is extensible. For example, adding nullability:
type Nullable<T> = {
[P in keyof T]: T[P] | null;
};
Or filtering out certain types:
type ExcludeStrings<T> = {
[P in keyof T as T[P] extends string ? never : P]: T[P];
};
Understanding the core concept of Mapped Types opens doors to creating diverse, reusable types.
Recursion
Recursion is a cornerstone in TypeScript's type-level programming, especially since state mutation is not an option. Consider applying immutability to all nested properties:
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends object ? DeepReadonly<T[P]> : T[P];
};
Here, TypeScript's compiler recursively ensures every property is immutable, demonstrating the language's depth in handling complex types.
Union Types
Union Types represent a set of distinct types, such as:
type Status = 'Failure' | 'Success';
Creating structured types from unions involves looping over each union member. For instance, constructing a type where each status is an object:
type StatusObject = Status extends infer S ? { status: S } : never;
Conclusion
TypeScript's advanced type system transcends static type checking, providing sophisticated tools for type transformation and manipulation. Mapped Types, Recursion, and Union Types are not mere features but powerful instruments that enhance code maintainability, type safety, and expressiveness. These techniques underscore TypeScript's capability to elegantly handle complex programming scenarios, affirming its status as more than a JavaScript superset but a language that enriches our development experience.
Enjoyed this post? Follow me on X for more Vue and TypeScript content:
Top comments (8)
quick and on the point, no bla bla. Very good, Sir 👌 I like, how it's possible to "play around" with types. Sometimes it feels well boilerplated, but when you onboard a new coworker and he don't mess with the code, you know why it was worth it.
Thanks! Yeah, I think most of the advanced stuff from TypeScript is needed only for libraries. But it's fun to do fancy stuff with it.
What does "infer" do here? In the last example.
It infers whatever type can be extended from the type Status. In this case it is the strings Failure or Success.
Then the never at the end of the ternary is just to tell the typescript compiler that there never will be anything that does not extend Status
Great post!
Typescript has a
Readonly<T> utility type
that does what you specified above without the need for manual implementation. Typescript offers a lot of other useful utility types.It's better if give example code too :D
I think DeepReadonly should look like this
interesting both solutions works why do you like yours more?
Some comments have been hidden by the post's author - find out more