Javascript 为规范json提供index.d.ts文件?

Javascript 为规范json提供index.d.ts文件?,javascript,typescript,npm,types,Javascript,Typescript,Npm,Types,我正在尝试为创建一个index.d.ts文件。这就是我所拥有的: declare module 'canonical-json' { export function stringify(s: any): string; } 还尝试: declare namespace JSON { export function stringify(s:any):string; } export = JSON; 及 然而,我得到: canonical_json_1.stringify不是一个函

我正在尝试为创建一个
index.d.ts
文件。这就是我所拥有的:

declare module 'canonical-json' {
    export function stringify(s: any): string;
}
还尝试:

declare namespace JSON {
  export function stringify(s:any):string;
}

export = JSON;

然而,我得到:

canonical_json_1.stringify不是一个函数

所有三次尝试

这是stackblitz:

由于这是一个常见的js模块,其中整个导出是一个对象,因此您可以使用特定的
export=
语法:

// src\@types\canonical-json\index.d.ts
declare module 'canonical-json' {
    function stringify(s: any): string;
    export = stringify;
}
// index.ts
import stringify = require('canonical-json');
您还可以启用
“esModuleInterop”:true
以作为默认导入访问导出:

// src\@types\canonical-json\index.d.ts
declare module 'canonical-json' {
    function stringify(s: any): string;
    export = stringify;
}
// index.ts
import stringify from 'canonical-json';
最后一个选项是使定义仅具有默认导出,您仍然需要
“esModuleInterop”:true
,因为模块实际上没有默认导出:

// src\@types\canonical-json\index.d.ts
declare module 'canonical-json' {
    export default function stringify(s: any): string;
}

// index.ts
import stringify from 'canonical-json';

注意:我在node中测试了所有这些配置,但我希望在其他环境中也能使用相同的配置。

你当然是对的,但我不明白为什么要使用环境外部模块声明。这主意太糟糕了,因为我把它改成了第一个选项。我可以将
导出
函数
放在同一行,否则stackblitz会画一条红线,并将导入从“canonical json”更改为
导入stringify
现在它似乎正在工作,但是Stackblitz在
stringify
下面画了一条红色的曲线,上面有这样一条消息
无法调用类型缺少调用签名的表达式。类型“typeof import”(“canonical json”)”没有兼容的调用签名。
我用
default
尝试了第三个选项,效果很好。我再也不会在
stringify
下看到红色的蠕动。
// src\@types\canonical-json\index.d.ts
declare module 'canonical-json' {
    export default function stringify(s: any): string;
}

// index.ts
import stringify from 'canonical-json';