DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for TypeScript: ensure your strings are in the right format
Johan du Toit
Johan du Toit

Posted on

TypeScript: ensure your strings are in the right format

Turns out TypeScript allows you to type your string formats...

Example #1

type MyStringFormat = `${number} ${string} ${number}`;
const valid: MyStringFormat = "1 b 3"
const invalid: MyStringFormat = "a b c"
Enter fullscreen mode Exit fullscreen mode

Example #2

type Unit = 'C' | 'F' | 'K'

type Temp = `${number} ${Unit}`;
const validTemp: Temp = "273 K" // 0 C, 31.73 F
const invalidTemp: Temp = "0 B" // 0C, 31.73F, 273K (no spaces)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.