My question is very brief. I am new to TypeScript, been searching around here and there but didn't find yet an answer.

Does any experienced TypeScripter know if there is a character Type or an easy way to achieve one?


TypeScript does not have a type for representing fixed-length strings.


I'm not sure about easy, but you could sorta do something with string literal types:

type Char = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' 
| 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' 
| 'y' | 'z' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G' | 'H' | 'I' | 'J' | 'K' 
| 'L' | 'M' | 'N' | 'O' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'U' | 'V' | 'W' | 'X' 
| 'Y' | 'Z' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' // etc....;

of course, this is a fairly brittle solution and breaks down when you consider unicode characters, and I wouldn't really suggest it. As Ryan mentions, JavaScript itself doesn't have any notion of a fixed length string, nor the concept of a char as distinct from a string.


You could use a regex within TypeGuard to contain it's type eg:(you can declare an empty enum to get a new type to be associated with the type guard)

enum CharType { }
export type Char = string & CharType 
const isChar=(str: string): str is Char => /^(.|\n)$/.test(
  str
)
export char(c:string):Char{
//you can also use is char here for to test whether actually is char
   if (!isChar(c)){
       throw new Error('not a char')
   }
   return c
}

Now Char matches only things that come from calling char(eg actually casted by calling the function rather than just asserted on build time. The compiler simply accepts that a Char is returned and that's actually true if you think of it since it will just throw otherwise)

Original Source(applied to date string): Atomic Object

Assumptions: I assume that by mentioning typescript you mean a type used for compile-time checks by typescript compiler and not looking for any kind of optimization on the actual compiled js side(since js only has strings)

The only issue I can see is that you can pass whatever to char function and it will only throw at run time. But you will never reach to a state where you expect a Char and you get something else(since Chars only come from calling char).

On a side note even java casts throw just runtime exceptions.

Although the above approach might not have much to do with casts, I do find some commonalities...