Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to specify string format with TypeScript?

I just wonder - is it a way to check if the string matches some pattern via TypeScript.

I don't want to do the checks in the runtime.

//What I have now
public id: string; //can be whatever string 

//What I want to see
public id: IdType; //Some type?
id = '0000-0000-0000-0001'//valid
id = 'whatever'//invalid

So is it a way to define string format?

like image 840
Sergei Panfilov Avatar asked Nov 08 '17 10:11

Sergei Panfilov


People also ask

Is there a string format in TypeScript?

TypeScript doesn't add to the native objects, so it also doesn't have a String. format function.

How do you define a string type in TypeScript?

In TypeScript, the string is sequence of char values and also considered as an object. It is a type of primitive data type that is used to store text data. The string values are used between single quotation marks or double quotation marks, and also array of characters works same as a string.


1 Answers

This should now be possible as of TS 4.1 beta

There's now a feature called Template Literal Types, which looks something like this (excuse the basic example):

type idType = `${number}-${number}-${number}-${number}`
const id: idType = '0000-0000-0000-0001';

https://devblogs.microsoft.com/typescript/announcing-typescript-4-1-beta/#template-literal-types

Playground

like image 80
Daniel Del Core Avatar answered Oct 26 '22 07:10

Daniel Del Core