【问题标题】:def file for object export and types用于对象导出和类型的 def 文件
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 嘿马特,这种方法的问题是我不能使用similarity.compareTwoStrings() 的方法。尝试执行import similarity from "string-similarity" 之类的操作,并且还能够访问这些类型。
    • @LukePighetti 你应该可以通过import * as similarity from "string-similarity";实现这一目标
    • 好的,我现在明白了。谢谢。
    • @LukePighetti 我已将其添加为答案,如果它解决了您的问题,请随时接受。
    【解决方案2】:

    要在一个共同的父级下访问您的方法(例如 similarity),您需要在similarity 别名下导入它们:

    import * as similarity from "string-similarity"; 
    
    similarity.compareTwoStrings("potato", "tomato");
    

    【讨论】:

      猜你喜欢
      • 2010-09-16
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 2019-09-24
      • 2012-01-07
      • 2012-11-25
      相关资源
      最近更新 更多