I'm new to typescript, but understand javascript. I'm building a simple utility class that will change the ASCII color of the terminal output. I want the function to be callable like this:
Colorize(ColorizeColors.Red).and(ColorizeBackgrounds.BrightBlue).on('hello world');
Ideally, I would like to be able to pass either a ColorizeColors or ColorizeBackground object to both the initial function call and the .and function and have it work either way. The .on function gets the string text and returns the colorized string. I have created this enums with the correct codes:
export enum ColorizeColors {
Black = "\u001b[30m",
Red = "\u001b[31m",
Green = "\u001b[32m",
Yellow = "\u001b[33m",
Blue = "\u001b[34m",
Magenta = "\u001b[35m",
Cyan = "\u001b[36m",
White = "\u001b[37m",
BrightBlack = "\u001b[30;1m",
BrightRed = "\u001b[31;1m",
BrightGreen = "\u001b[32;1m",
BrightYellow = "\u001b[33;1m",
BrightBlue = "\u001b[34;1m",
BrightMagenta = "\u001b[35;1m",
BrightCyan = "\u001b[36;1m",
BrightWhite = "\u001b[37;1m",
Reset = "\u001b[0m",
}
export enum ColorizeBackgrounds {
Black = "\u001b[40m",
Red = "\u001b[41m",
Green = "\u001b[42m",
Yellow = "\u001b[43m",
Blue = "\u001b[44m",
Magenta = "\u001b[45m",
Cyan = "\u001b[46m",
White = "\u001b[47m",
BrightBlack = "\u001b[40;1m",
BrightRed = "\u001b[41;1m",
BrightGreen = "\u001b[42;1m",
BrightYellow = "\u001b[43;1m",
BrightBlue = "\u001b[44;1m",
BrightMagenta = "\u001b[45;1m",
BrightCyan = "\u001b[46;1m",
BrightWhite = "\u001b[47;1m",
Reset = "\u001b[0m",
}
This is a quick try of some pseudo-Javascript code of the way that I would think it would be implemented, but I can't get it to work in real Typescript.
function Colorize (color: ColorizeColors | ColorizeBackgrounds) {
if (typeof color === ColorizeColors) {
this.fg = color;
} else if (typeof color === ColorizeBackgrounds) {
this.bg = color;
}
return this;
}
Colorize.and = function (color: ColorizeColors | ColorizeBackgrounds) {
if (typeof color === ColorizeColors) {
this.fg = color;
} else if (typeof color === ColorizeBackgrounds) {
this.bg = color;
}
return this;
}
Colorize.on = function (text: string) {
return `${this.bg}${this.fg}${text}${ColorizeColors.Reset}`;
}
I have gotten the function to work correctly with other styles of calling it, such as
Colorize.text(ColorizeColors.Red).bg(ColorizeBackgrounds.BrightBlue).on('hello world')
but I like the first style better and am trying to understand how to produce it as an exercise.
ColorizeColors.ResetandColorizeBackgrounds.Resetare the same so you can't figure out if it's foreground or background. Is that important? If I callColorize(ColorizeColors.Reset)what is supposed to happen?