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

时间:2018-09-30 23:01:50

标签: typescript typescript-typings

好的,所以我们有一个节点模块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;
}

string-likeity.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);
  });
});

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

要在公共父项(例如 similarity)下访问方法,则需要在similarity别名下导入它们:

import * as similarity from "string-similarity"; 

similarity.compareTwoStrings("potato", "tomato");