gpt4 book ai didi

javascript - 为 canonical-json 提供 index.d.ts 文件?

转载 作者:行者123 更新时间:2023-12-02 23:18:57 25 4
gpt4 key购买 nike

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

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

还尝试过:

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

export = JSON;

还有

export as namespace JSON;
export const stringify: (o:any) => string;

但是我得到:

canonical_json_1.stringify is not a function

对于所有三次尝试。

这是堆栈 Blitz : https://stackblitz.com/edit/typescript-cryptojs?file=src%2F%40types%2Fcanonical-json%2Findex.d.ts

最佳答案

由于这是一个常见的 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';

注意:我在节点中测试了所有这些配置,但我希望在其他环境中也能同样工作。

关于javascript - 为 canonical-json 提供 index.d.ts 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57032253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com