TypeScript character type?

38,688

Solution 1

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

Solution 2

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

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

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

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.

Share:
38,688
charliebrownie
Author by

charliebrownie

I am a Software Engineer with strong interest in: Clean Code and good practices the whole Software Development Process Web Development & Technologies "Life is about creating yourself." "Do what you love, love what you do."

Updated on July 05, 2022

Comments

  • charliebrownie
    charliebrownie almost 2 years

    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?

  • Bergi
    Bergi about 7 years
    But it's not any number, it's an unsigned 16 bit integer at least.
  • cocoseis
    cocoseis about 7 years
    so, how does that matter?
  • Bergi
    Bergi about 7 years
    It matters because it means we cannot use the builtin number type
  • tensojka
    tensojka almost 7 years
    Note that Number is a floating point value of undefined length. Do not expect better performance.
  • Andreas
    Andreas almost 6 years
    Typescript is so powerful, If you ever think of a type you can't express you might be wrong.
  • Callat
    Callat almost 6 years
    To sort of "extend" the dialog here. Typescript expands on statically typing the native types of javascript. Javascript does not have a char type. So type-script doesn't have a char type.
  • Patrick Roberts
    Patrick Roberts over 5 years
    If only string & { length: 1 } could be statically inferred... I tried but it throws an error when trying to assign any one-character string to a variable of that type.
  • Raine Revere
    Raine Revere over 3 years
    May work on an individual Char, but if you try to use a string, you'll get Type 'string' is not comparable to type 'Char[]'.
  • Ambrus Tóth
    Ambrus Tóth over 3 years
    Nice solution. XDDD
  • R. Wang
    R. Wang over 2 years
    While it's a bit late, you may also want to override toString() so that it concatenate properly with other strings