TypeScript character type?

JavascriptTypescriptTypescript Typingstypescript2.0

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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...

Solution 4 - Javascript

A Char is simply a number. Since the basic types of TypeScript do not include Chars what you could do is store a number and convert it back and forth:

var number = "h".charCodeAt(0);
var char = String.fromCharCode(number)


And to something like:

class Char {
    private _value:Number;
    
    constructor(char: Number | String){
        this.setValue(char);
    }
    
    get getValue():String {
        return String.fromCharCode(this._value);
    }
    set setValue(char: Number | String) {
          if (typeof char === "number") {
              this._value = char;
          }
          else {
            this._value = char.charCodeAt(0);
          }
    }
}

Solution 5 - Javascript

As I know, the basic types of typescript don't include char.

Solution 6 - Javascript

You could just define a wrapper around string, and throw an error if the string is more than one character.

class Character {
    readonly char: string;
    constructor(char: string) {
        if(char.length !== 1) {
           throw new Error(char + " is not a single character");
        }
    
        this.char = char;
    }
    
    toString(): string {
       return this.char;
    }
}

////////////////////////////////////////
var good: Character = new Character("f");
var bad: Character = new Character("foo"); //error

Of course, you can also add helper methods to the class which operate on the string like toLowerCase(), toUpperCase(), etc.

Solution 7 - Javascript

As a slightly more concise method than listing out all letter characters, you can list out all upper-case or all lower-case characters, then use Lowercase or Uppercase to change their capitalization and unify with the previous type.

type UpperCaseCharacter = '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'
// add additional non-letter characters to this union as desired
type Character = UpperCaseCharacter | Lowercase<UpperCaseCharacters>;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncharliebrownieView Question on Stackoverflow
Solution 1 - JavascriptRyan CavanaughView Answer on Stackoverflow
Solution 2 - JavascriptrossipediaView Answer on Stackoverflow
Solution 3 - JavascriptAndreasView Answer on Stackoverflow
Solution 4 - JavascriptcocoseisView Answer on Stackoverflow
Solution 5 - JavascriptzhangjinzhouView Answer on Stackoverflow
Solution 6 - JavascriptNirvanaView Answer on Stackoverflow
Solution 7 - JavascriptCertainPerformanceView Answer on Stackoverflow