【发布时间】:2018-10-01 23:05:17
【问题描述】:
好的,所以我们有一个 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。尽管我可以看到方法很好,没有红色曲线。
index.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);
});
});
【问题讨论】:
标签: typescript typescript-typings