如何获取Chalk支持的所有颜色的名称?

Gar*_*ary 5 types type-assertion typescript chalk

我在 TypeScript 中使用Chalk NPM 包。如果我动态设置 Chalk 的颜色,则会收到 TS 错误。我可以使用类型断言,chalk[color] as Chalk但如果可能的话,我更愿意使用类型谓词,这需要我能够访问支持的颜色列表。

那么,有没有一种方法可以访问 Chalk 中支持的颜色列表,或者有其他方法来解决这个问题,而不使用类型断言,并且可能使用类型谓词?

可能需要启用instrict中的选项才能显示错误。compilerOptionstsconfig.json

代码如下,错误在注释中:

import chalk from 'chalk';

function getColor(): string {
  return 'blue';
}

const color = getColor();

/**
 * Element implicitly has an 'any' type because expression of type 'string'
 * can't be used to index type 'Chalk & { supportsColor: ColorSupport; }'.
 *
 * No index signature with a parameter of type 'string' was found on type 'Chalk
 * & { supportsColor: ColorSupport; }'.ts(7053)
 */
console.log(chalk[color]('test'));
Run Code Online (Sandbox Code Playgroud)

Ole*_*ter 2

是的,这是可能的,而且您甚至不需要类型谓词。

Chalk 导出两种联合类型,分别定义支持的前景和背景类型:ForegroundColorBackgroundColor(以及方便的联合类型Color)。您可以简单地导入它们并将其中之一(或两者)添加为函数的返回类型getColor

import chalk, { type ForegroundColor, type BackgroundColor } from 'chalk';

function getColor(): ForegroundColor | BackgroundColor {
  return 'blue';
}

const color = getColor();

console.log(chalk[color]('test')); // OK
Run Code Online (Sandbox Code Playgroud)

操场