首页 > 解决方案 > 用于对象导出和类型的 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);
  });
});

标签: typescripttypescript-typings

解决方案


看起来这export { ... }条线正在限制出口。(我不知道可以在一个declare module块中执行此操作!)如果我删除该行,那么默认情况下所有内容都会被导出并且我可以访问这些类型。


推荐阅读