-1

我有一个模块可以chalk根据我的特定需求修补颜色。这是代码:

import { ChalkStyleElement, ChalkStyleMap, styles } from 'chalk';
import escape from './escape';

/**
 * Decorate ASCII-colors with shell-specific escapes
 */
let PatchedChalkStyleMap: ChalkStyleMap;

Object.keys(styles).forEach((style: string) => {
  PatchedChalkStyleMap[style] = {
    close: escape(styles[style].close),
    open: escape(styles[style].open),
    reset: escape(styles[style].reset),
  };
});

上面我只是浏览了所有chalk样式并用我的特殊escape功能修补它们。但是,这不会编译。我收到这些错误:

src/colors.ts(10,3): error TS7017: Element implicitly has an 'any' type because type 'ChalkStyleMap' has no index signature.
src/colors.ts(11,16): error TS7017: Element implicitly has an 'any' type because type 'ChalkStyleMap' has no index signature.
src/colors.ts(12,15): error TS7017: Element implicitly has an 'any' type because type 'ChalkStyleMap' has no index signature.
src/colors.ts(13,16): error TS7017: Element implicitly has an 'any' type because type 'ChalkStyleMap' has no index signature

另外,我应该说我"noImplicitAny"tsconfig.json.

我怎样才能在这里正确地描述类型,而不是隐含的any

4

1 回答 1

-1

您可以扩充ChalkStyleMap界面以添加索引签名:

declare module "chalk" {
    interface ChalkStyleMap {
        [key: string]: ChalkStyleElement
    }
} 

如果你不想修改ChalkStyleMap接口,你可以扩展ChalkStyleMap到你的自定义接口,但是你必须在你使用的任何地方使用类型断言styles来确保编译器不会抛出错误:

interface YourChalkStyleMap extends ChalkStyleMap {
  [key: string]: ChalkStyleElement
}

let PatchedChalkStyleMap: YourChalkStyleMap;

接口合并见官方文档

于 2017-06-27T09:09:42.987 回答