好了,所以我们有一个Node模块string-similarity
,它可以导出两个这样的函数(请参阅:https : //github.com/aceakash/string-likeity/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
。即使我可以看到这些方法很好,也没有红色花线。
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;
}
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);
});
});
要在公共父级(例如 similarity
)下访问您的方法,您需要在similarity
别名下导入它们:
import * as similarity from "string-similarity";
similarity.compareTwoStrings("potato", "tomato");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句