Trim Left in TypeScript

Example of TrimLeft use

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:

For strings we need several concepts:

  1. Type inference in conditional types to infer substrings without whitespaces.
  2. Template Literal types to match substrings in a string.

First, letโ€™s declare Whitespace which will be removed from the beginning:

Whitespace example

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:

Example with removing one whitespace

Not all test cases are completed because we donโ€™t remove whitespaces after the first one. Letโ€™s apply the type recursively:

Solution

Thatโ€™s it ๐Ÿ’ช

The solution is available in Playground

Have a good day and week ๐ŸŒค

typescriptmedium

Let's chat and have fun ๐Ÿง‘โ€๐Ÿ’ป๐Ÿ‘ฉโ€๐Ÿ’ป

No more often than once a week I write ๐Ÿ“„ about TypeScript ๐Ÿ’ช, video playback ๐Ÿ“บ and frontend related topics. You can unsubscribe in any time โ†˜๏ธ

ยฉ 2021, Built with Gatsby