为什么以下代码在TypeScript中给出了声明错误?

时间:2018-05-05 01:03:02

标签: typescript

我正在尝试使用以下模块:

https://github.com/andyhu/transliteration

当我尝试:

import { transliterate as tr, slugify } from 'transliteration';

我明白了:

error TS7016: Could not find a declaration file for module 'transliteration'.

如何解决此错误?

2 个答案:

答案 0 :(得分:0)

  

如何解决此错误?

因为包中没有TypeScript类型定义。

修复

尝试npm install @types/transliteration如果这不起作用simply create

declare module 'translitereation'; 

答案 1 :(得分:0)

更新:现在可以从DefinitelyTyped获取这些类型。只需运行以下命令即可解决类型错误:

npm i -D @types/transliteration

GitHub项目没有公开类型,因此您必须在项目中创建自己的本地类型(请参阅下面的快速修复)。我有一个DefinitelyTyped PR可以发布新的拼贴版本,以便您能够安装它们(使用npm i @types/transliteration),而不是维护自己的。

快速修复:使用以下内容创建<project-root>/index.d.ts

declare module 'transliteration' {
  function transliterate(str: string, options?: transliterate.Options): string;

  namespace transliterate {
    /**
    * Bind options globally so any following calls will be using
    * optionsObj by default. If optionsObj argument is omitted,
    * it will return current default option object.
    */
    function config(optionsObj?: Options): Options;

    interface Options {

      /**
      * Unicode characters that are not in the database will be replaced with `unknown`
      * default: "[?]"
      */
      unknown?: string;

      /**
      * Custom replacement of the strings before transliteration
      */
      replace?: string[][] |  {[source: string]: string};

      /**
      * Strings in the ignore list will be bypassed from transliteration
      */
      ignore?: string[];
    }
  }

  function slugify(str: string, options?: slugify.Options): string;

  namespace slugify {
    /**
    * Bind options globally so any following calls will be using
    * optionsObj by default. If optionsObj argument is omitted,
    * it will return current default option object.
    */
    function config(optionsObj?: Options): Options;

    interface Options {

      /**
      * Whether to force slugs to be lowercased
      * default: true
      */
      lowercase?: boolean;

      /**
      * Separator of the slug
      * default: "-"
      */
      separator?: string;

      /**
      * Custom replacement of the strings before transliteration
      */
      replace?: string[][] |  {[source: string]: string};

      /**
      * Strings in the ignore list will be bypassed from transliteration
      */
      ignore?: string[];
    }
  }
}