Trim left part of string literal type in TypeScript
10 May 2021
Today we discuss Trim Left
String.prototype.trimStart does the same in JavaScript what we are about to do in TypeScript.
Let's try 👩💻
Iteration over a string
We already know how to iterate over:
- Object types (see Pick under the hood)
- Tuple types (see Making object out of tuple)
- Union types (see Exclude under the hood)
For strings we need several concepts:
- Type inference in conditional types to infer substrings without whitespaces.
- Template Literal types to match substrings in a string.
First, let's declare Whitespace
which will be removed from the beginning:
Second, let's try to remove the first whitespace if it is a part of a string we pass. We will get something like this:
Not all test cases are completed because we don't remove whitespaces after the first one. Let's apply the type recursively:
That's it 💪
The solution is available in Playground
Have a good day and week 🌤
typescript