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?
TypeScript doesn't add to the native objects, so it also doesn't have a String. format function.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With