I'm using the Chalk NPM package in TypeScript. If I dynamically set the color for Chalk, then I get a TS error. I could use a type assertion like chalk[color] as Chalk
but I would prefer to use a type predicate if possible, which would require for me to be able to access the list of supported colors.
So, is there a way to access the list of supported colors in Chalk, or another way to resolve this issue, without using type assertions, and possibly using type predicates?
The strict
option in compilerOptions
in tsconfig.json
may need to be enabled, to get the error to appear.
The code is below, and the error is in the comments:
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'));
Yes, it is possible, and you do not even need a type predicate.
Chalk exports two union types that define supported foreground and background types: ForegroundColor
and BackgroundColor
respectively (as well as a convenience union type Color
). You can simply import them and add one of them (or both) as the return type of your getColor
function:
import chalk, { type ForegroundColor, type BackgroundColor } from 'chalk';
function getColor(): ForegroundColor | BackgroundColor {
return 'blue';
}
const color = getColor();
console.log(chalk[color]('test')); // OK