Search code examples
javascriptnode.jstypescripttypeschalk

TypeScript error when dynamically setting color for `chalk` package


The chalk package is very popular for terminal styles in Node.

I'm using TypeScript. I'm trying to set the color dynamically. But I am getting a TS error on compile.

Code:

import chalk, { Chalk } from 'chalk';

function getColor(): keyof Chalk {
  let color: keyof Chalk = 'green';

  color = 'yellow';

  return color;
}

const chalkColor = getColor();

// Error on `chalk[chalkColor]`
console.log(chalk[chalkColor]('message'));

Error (on chalk[chalkColor]):

This expression is not callable.
  Not all constituents of type 'boolean | (Chalk & { supportsColor: ColorSupport; }) | (ChalkConstructor & Function) | Level | ((r: number, g: number, b: number) => Chalk & { supportsColor: ColorSupport; }) | ... 10 more ... | ((color: string) => Chalk & { ...; })' are callable.
    Type 'false' has no call signatures.

How can I resolve this error?


Solution

  • Okay, so I figured this out soon after. But I'll leave this question up, just in case someone has a better solution. I used an enum containing the colors I intended to use. That seemed to fix the issue.

    import chalk from 'chalk';
    
    enum ChalkColor {
      Green = 'green',
      Yellow = 'yellow',
    }
    
    function getColor(): ChalkColor {
      let color = ChalkColor.Green;
    
      color = ChalkColor.Yellow;
    
      return color;
    }
    
    const chalkColor = getColor();
    
    console.log(chalk[chalkColor]('message'));
    

    The other solution is to use (chalk[chalkColor] as Chalk), like so:

    import chalk, { Chalk } from 'chalk';
    
    function getColor(): keyof Chalk {
      let color: keyof Chalk = 'green';
    
      color = 'yellow';
    
      return color;
    }
    
    const chalkColor = getColor();
    
    console.log((chalk[chalkColor] as Chalk)('message'));