Search code examples
node.jstypescriptchalk

Dynamic call of chalk with typescript


I am using typescript and want to call the chalk method dynamically, see my code :

import chalk from 'chalk';

const color: string = "red";
const message: string = "My Title";
const light: boolean = false;

const colorName = `bg${capitalize(color)}${light ? 'Bright' : ''}`;
console.log(chalk[colorName](message));

So, the color function takes as a value the color of the background of the message. The message is the content and the light is the boolean used to know if the background should have its bright version used.
The problem is that typescript throws this error :

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'ChalkInstance'.

on the chalk[colorName] part.

I already tried to put (chalk[colorName] as keyof ChalkInstance). And already looked at this post (which is the basically the same problem). Obviously, the solutions answered aren't working with my case.


Solution

  • I found the answer to my question myself. The problem was that the colorName variable was of type any and chalk couldn't recognize it as an index of the chalk class. Here the value of the colorName variable could contain all the value of the backgroun colors whether they were bright or not.
    I then had two solutions :

    • Hard code all the values of the colors (which would take a long time)
    • Find the type representing the colors and explicit set as the type of the colorName variable

    My solution is close from the second idea, however, the Chalk library doesn't provide a type for the colors. However, we can import the explicit list of all the BackgroundColors. Then, we only have to asign the type of these keywors as the type of the colorName variable.

    import { BackgroundColor } from 'chalk';
    
    import chalk from 'chalk';
    
    const color: string = "red";
    const message: string = "My Title";
    const light: boolean = false;
    
    const colorName = `bg${capitalize(color)}${light ? 'Bright' : ''}` as typeof BackgroundColor;
    console.log(chalk[colorName](message));
    

    PS: Note that the type of the variabkes color, message and light are hard-coded. On the application, these values are dynamic, that's a way to make it more clear.