用于对象导出和类型的 def 文件 [英] def file for object export and types

查看:39
本文介绍了用于对象导出和类型的 def 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我们有一个 Node 模块 string-similarity,它导出两个这样的函数(参见:https://github.com/aceakash/string-similarity/blob/master/compare-strings.js#L7-L8 )

Alright, so we have a Node module string-similarity who exports two functions like this (see: https://github.com/aceakash/string-similarity/blob/master/compare-strings.js#L7-L8 )

module.exports = { compareTwoStrings, findBestMatch }

我整理了一个运行良好的定义文件,只是我无法访问类型.

I have put together a definition file that works quite well, except I cannot access the types.

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 文件?

I am very new to Typescript so my question is this: should I be able to import these types? I would think so. And also, is there an idiomatically correct way to create this def file?

我能够让 VSC 中的智能感知认为我已经解决了问题,但我仍然收到错误 TypeError:无法读取未定义的属性 'compareTwoStrings'.尽管我可以看到方法很好并且没有红色波浪线.

I was able to get the intellisense in VSC to think I had solved the problem, but I still get the error TypeError: Cannot read property 'compareTwoStrings' of undefined. Even though I can see the methods just fine and no red squiggles.

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-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);
  });
});

推荐答案

要在公共父级(eg similarity)下访问您的方法,您需要将它们导入到similarity 别名:

To access your methods under a common parent (e.g. similarity), you need to import them under the similarity alias:

import * as similarity from "string-similarity"; 

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

这篇关于用于对象导出和类型的 def 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆