gpt4 book ai didi

typescript - 用于对象导出和类型的 def 文件

转载 作者:搜寻专家 更新时间:2023-10-30 21:11:53 26 4
gpt4 key购买 nike

好的,所以我们有一个 Node 模块 string-similarity 导出两个像这样的函数(参见:https://github.com/aceakash/string-similarity/blob/master/compare-strings.js#L7-L8)

module.exports = { compareTwoStrings, findBestMatch }

我已经整理了一个运行良好的定义文件,但我无法访问这些类型。

declare module "string-similarity" {
function compareTwoStrings(string1: string, string2: string): number;

function findBestMatch(string: string, targetStrings: string[]): Result;

interface Result {
ratings: Match[];
bestMatch: Match;
}

interface Match {
target: string;
rating: number;
}

export { compareTwoStrings, findBestMatch };
}

我是 Typescript 的新手,所以我的问题是:我应该能够导入这些类型吗?我会这么认为。另外,是否有一种惯用的正确方法来创建此 def 文件?

更新

我能够让 VSC 中的智能感知认为我已经解决了问题,但我仍然收到错误 TypeError: Cannot read property 'compareTwoStrings' of undefined。尽管我可以看到这些方法很好,没有红色波浪线。

索引.d.ts

declare module "string-similarity" {
namespace similarity {
function compareTwoStrings(string1: string, string2: string): number;

function findBestMatch(string: string, targetStrings: string[]): Result;
}

export interface Result {
ratings: Match[];
bestMatch: Match;
}

export interface Match {
target: string;
rating: number;
}

export default similarity;
}

字符串相似度.spec.ts

import similarity from "string-similarity";
import { Result, Match } from "string-similarity";

describe("compare two strings", () => {
it("works", () => {
const string1 = "hello";
const string2 = "dello";

const result: number = similarity.compareTwoStrings(string1, string2);

expect(result).toBe(0.75);
});
});

最佳答案

看起来 export { ... } 行限制了导出。 (我不知道可以在 declare module block 中执行此操作!)如果我删除该行,则默认情况下会导出所有内容并且我能够访问类型。

关于typescript - 用于对象导出和类型的 def 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52582848/

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