我在TypeScript中使用的是NPM软件包。如果我动态地为Chalk设置颜色,那么我将得到一个TS错误。我可以使用类似于chalk[color] as Chalk
的类型断言,但如果可能的话,我更愿意使用类型谓词,这需要我能够访问受支持的颜色列表。
那么,是否有一种方法可以访问Chalk中支持的颜色列表,或者另一种解决此问题的方法,而不使用类型断言,或者可能使用类型谓词?
可能需要启用compilerOptions
中的compilerOptions
中的tsconfig.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'));
发布于 2022-05-29 22:20:40
是的,这是可能的,而且您甚至不需要类型谓词。
粉笔导出两种联合类型,它们分别定义支持的前台和后台类型:ForegroundColor
和BackgroundColor
(以及方便的联合类型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
https://stackoverflow.com/questions/58650124
复制相似问题