enum CharType { }
export type Char = string & CharType
const isChar = (str: string): str is Char => /^(.|\n)$/.test(
str
)
export function toChar(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
}
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