typescript - 用于对象导出和类型的 def 文件
问题描述
好的,所以我们有一个 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
块中执行此操作!)如果我删除该行,那么默认情况下所有内容都会被导出并且我可以访问这些类型。
推荐阅读
- python - 在 Python 中将交互列表转换为矩阵
- powershell - 基于时间的while循环
- git - 有没有办法让一个存储库由来自两个复制的存储库的文件组成,这些存储库继续从 github 上的两个独立存储库更新?
- javascript - 等待后,console.log 不返回异步结果
- python - 无法删除“Unmamed:”行
- c# - 将 SQL 日期时间与 C# DateTime.Now 进行比较
- ruby-on-rails - 使用 Active Record 的 Graphql-Ruby 映射
- asp.net - 在 asp.net 上加载 ReactJS 视图问题与图像路径
- reactjs - 热重载无法与 React-Redux 和 Hooks 一起正常工作
- html - 如何使网格居中并将上方的行与其左侧对齐?