String Patterns in TypeScript
Saulo Dias

Saulo Dias @saulodias

About: Software Developer graduated in Automation and Control Engineering trying way too hard to become a brogrammer.

Location:
Rio de Janeiro, Brazil
Joined:
Apr 29, 2021

String Patterns in TypeScript

Publish Date: Sep 28 '21
5 0

While we wait for a regex type in TypeScript, starting on TypeScript 4.1 we can make use of a very neat trick to create string patterns validations which can come in handy for some simple use cases.

I'm using Leonardo Victor's approach to query endpoints in multiple APIs using the Angular HttpClient.

By making use of string patterns I'm able to validate the urls to some extent.

type ApiAlias = 'my-api' | 'third-party-api' | 'another-api';

type ApiUrl = `@${ApiAlias}/${string}`;

const MY_ENDPOINT: ApiUrl = '@my-api/myendpoint';

const ANOTHER_ENDPOINT: ApiUrl = '@thirdparty-api/anotherendpoint';
Enter fullscreen mode Exit fullscreen mode

TypeScript Playground

ANOTHER_ENDPOINT will throw an error because thirdparty-api has a typo. It's missing a hyphen, and should be third-party-api.

Go check out Leonardo Victor's post if you're interested in this implementation!

This post was inspired by this Stack Overflow thread. Let me know if things have changed by the time you're reading this, so I can keep this up to date.

Comments 0 total

    Add comment