Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a string that is of a specific length using typescript?

Tags:

typescript

For example a string that can only be two characters long, which could be used for an ISO country code.

I have used Google and looked through the documentation but cannot find the answer.

like image 691
user3336882 Avatar asked Aug 15 '17 18:08

user3336882


2 Answers

There isn't a way to specify a string length as a type.

If you have a finite list of country codes, you could write a string literal type:

type CountryCode = 'US' | 'CN' | 'CA' | ...(lots of others);
like image 97
Ryan Cavanaugh Avatar answered Oct 02 '22 16:10

Ryan Cavanaugh


You can achieve this using a type constructor and a phantom type which are some interesting techniques to learn about. You can see my answer to a similar question here

like image 40
cdimitroulas Avatar answered Oct 02 '22 15:10

cdimitroulas