TypeScript error when dynamically setting color for `chalk` package

5.3k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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'));
0
On

Actually it looks like Chalk makes it even easier that that currently.

https://developer.aliyun.com/mirror/npm/package/chalk

console.log( chalk.keyword(<colorVariableName>)(TextYouWantToLogOut) )