[英]In Typed JS (Typescript/FlowType) how do you handle normalized objects?
[英]How do you patch objects in TypeScript?
我有一个模块可以根据我的特定需求修补chalk
colors。 这是代码:
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
styles 并用我的特殊escape
function 修补它们。 但是,这不会编译。 我收到这些错误:
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
另外,我应该说我在tsconfig.json
中启用了"noImplicitAny"
选项。
我怎样才能在这里正确地描述类型,而不会隐含any
?
此方法将修补 object
PatchObject(patchableObj: Object, obj: Object) {
for (const [key, value] of Object.entries(obj)) {
if (value != null && value != undefined) {
(patchableObj as any)[key] = value
}
}
}
它在做什么? 它只是避免null
或undefined
的值。
您可以扩充ChalkStyleMap
接口以添加索引签名:
declare module "chalk" {
interface ChalkStyleMap {
[key: string]: ChalkStyleElement
}
}
如果您不想修改ChalkStyleMap
接口,您可以将ChalkStyleMap
扩展到您的自定义接口中,但是您必须在使用styles
的任何地方使用类型断言以确保编译器不会抛出错误:
interface YourChalkStyleMap extends ChalkStyleMap {
[key: string]: ChalkStyleElement
}
let PatchedChalkStyleMap: YourChalkStyleMap;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.