首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获得Chalk支持的所有颜色的名称?

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

Stack Overflow用户
提问于 2019-10-31 19:32:39
回答 1查看 415关注 0票数 5

我在TypeScript中使用的是NPM软件包。如果我动态地为Chalk设置颜色,那么我将得到一个TS错误。我可以使用类似于chalk[color] as Chalk的类型断言,但如果可能的话,我更愿意使用类型谓词,这需要我能够访问受支持的颜色列表。

那么,是否有一种方法可以访问Chalk中支持的颜色列表,或者另一种解决此问题的方法,而不使用类型断言,或者可能使用类型谓词?

可能需要启用compilerOptions中的compilerOptions中的tsconfig.json选项,以使错误出现。

代码在下面,错误出现在注释中:

代码语言:javascript
运行
复制
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'));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-29 22:20:40

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

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

代码语言:javascript
运行
复制
import chalk, { type ForegroundColor, type BackgroundColor } from 'chalk';

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

const color = getColor();

console.log(chalk[color]('test')); // OK

游乐场

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58650124

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档