1

chalk 包对于Node 中的终端样式非常流行。

我正在使用打字稿。我正在尝试动态设置颜色。但是我在编译时遇到了 TS 错误。

代码:

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

错误(开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.

如何解决此错误?

4

2 回答 2

1

实际上,Chalk 看起来比目前更容易。

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

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

于 2020-10-26T00:23:43.187 回答
0

好的,所以我很快就想通了。但我会留下这个问题,以防万一有人有更好的解决方案。我使用了一个包含我打算使用的颜色的枚举。这似乎解决了这个问题。

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

另一种解决方案是使用(chalk[chalkColor] as Chalk),如下所示:

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'));
于 2019-10-15T07:15:43.437 回答