Skip to content

Add trim as new intrinsic for use with template literal types #41283

Open
@hayes

Description

@hayes

Search Terms

intrinsic
trim
whitespace

possible related: #41210

Suggestion

Add trim as a new intrinsic alongside the existing intrinsic types:
Uppercase
Lowercase
Capitalize
Uncapitalize

Use Cases

Trim can be implemented with the current types pretty easily by doing something like:

type Whitespace = '\n' | ' ';
type Trim<T> = T extends `${Whitespace}${infer U}` ? Trim<U> : T extends `${infer U}${Whitespace}` ? Trim<U> : T;

But this can quickly run into depth limits if there is a lot of repeated whitespace.

type Whitespace = | '\n'|  ' ' | 'x' // Add x as whitespace to make example easier to read
type Trim<T> = T extends `${Whitespace}${infer U}` ? Trim<U> : T extends `${infer U}${Whitespace}` ? Trim<U> : T;
type Test = Trim<`abc
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
`>

This can be improved by adding strings of repeated whitespace to the Whitespace type, but will still run into limitations:

type Whitespace = | '\n' | '      ' | '     ' | '    ' | '   ' | '  ' | ' '
type Trim<T> = T extends `${Whitespace}${infer U}` ? Trim<U> : T extends `${infer U}${Whitespace}` ? Trim<U> : T;

This seems like a good case for an intrinsic implementation since it is a fairly simple and common operation on strings.

One use case would be to correctly type template literal helpers that trim leading indent whitespace, but there are probably many cases where trimming whitespace from a string would be useful.

Examples

Trim<`

   abc

`> // 'abc'

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions