[英]How to add typescript typings to NPM module that exports a class?
我希望我的design-systems-utils模块包括Typescript类型,即使源代码不是使用Typescript编写的(我已经看到其他人也这样做)。
我已经在这里尝试过了 ,但是没有用。 顺便说一下,我的模块导出了一个类...
declare class DesignSystem {
constructor(system: object, options?: object);
multiply(initial: number, multiplier: number): any;
get(val: string): any;
bp(bp: string): any;
z(z: string): any;
fontSize(size: string|number, toPxl?: boolean): string;
fs(size: string|number, toPxl?: boolean): string;
spacing(index: number): string;
space(index: number): string;
toPx(value: number, base: number, unit?: string): string;
pxTo(value: number, base: number): string;
color(hue:string, value:string): string;
designSystem: object;
interface options {
defaultUnit: string,
useModularScale: boolean,
fontSizeUnit: string
}
}
我还看到我应该将其导出为模块,如下所示:
declare module "DesignSystem" {
export default class DesignSystem {
constructor(system: object, options?: object);
/*~ Multiply two items together */
multiply(initial: number, multiplier: number): any;
get(val: string): any;
bp(bp: string): any;
z(z: string): any;
fontSize(size: string|number, toPxl?: boolean): string;
fs(size: string|number, toPxl?: boolean): string;
spacing(index: number): string;
space(index: number): string;
toPx(value: number, base: number, unit?: string): string;
pxTo(value: number, base: number): string;
color(hue:string, value:string): string;
designSystem: object;
}
}
但这也不起作用。
任何帮助将不胜感激。
原则上:
declare module "DesignSystem" { ...}
应该更改为您的npm模块的名称:
declare module "design-systems-utils" { ...}
这就是您告诉打字稿的方式“这是用户从设计系统-utils'导入...时的类型”。 当您需要从“外部”扩展库类型时,这最有用。
但是,由于您的package.json具有types: src/index.d.ts
字段,所以我们甚至不需要它。 Typescript已经知道您的d.ts
文件提供了哪些库定义。
export default class DesignSystem {...}
应该足够了。
您的第一次尝试声明一个名为DesignSystem的全局类。 一般的经验法则是,您的d.ts
应该镜像您的js结构。 因此,如果您确实要从js文件中export default
,也可以从d.ts
(此外,感谢您为图书馆提供了定义,您使世界变得更美好了)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.