如何为对象文字npm模块导出创建打字稿声明?

时间:2020-10-27 19:54:08

标签: typescript typescript-typings

我需要为npm模块制作一个.d.ts文件,我有这个npm模块https://github.com/jeremyckahn/keydrown I am writing keydrown.d.ts

它具有一个怪异的界面:

import KD from 'keydrown';
  KD.run(function KDRunTick() {KD.tick();});

  //Forward
  KD.W.press(() => dispatch({ type: "@INPUT/MOVE-FORWARD/PRESS" }));
  KD.W.up(() => dispatch({ type: "@INPUT/MOVE-FORWARD/UP" }));

  //Back
  KD.S.press(() => dispatch({ type: "@INPUT/MOVE-BACK/PRESS" }));
  KD.S.up(() => dispatch({ type: "@INPUT/MOVE-BACK/UP" }));

  //Left
  KD.A.press(() => dispatch({ type: "@INPUT/MOVE-LEFT/PRESS" }));
  KD.A.up(() => dispatch({ type: "@INPUT/MOVE-LEFT/UP" }));

///etc

我当前的.d.ts文件如下:

declare module 'keydrown' {
  interface KeyObject{
    press(callback: Function): void;
    up(callback: Function): void;
  }

  export default interface KD {
    run(callback: Function): void;
    ZERO:KeyObject
    ONE:KeyObject
    TWO:KeyObject
    THREE:KeyObject
    FOUR:KeyObject
    FIVE:KeyObject
    SEVEN:KeyObject
    EIGHT:KeyObject
    NINE:KeyObject
    A:KeyObject
    B:KeyObject
    C:KeyObject
    D:KeyObject
    E:KeyObject
    F:KeyObject
    G:KeyObject
    H:KeyObject
    I:KeyObject
    J:KeyObject
    K:KeyObject
    L:KeyObject
    M:KeyObject
    N:KeyObject
    O:KeyObject
    P:KeyObject
    Q:KeyObject
    R:KeyObject
    S:KeyObject
    T:KeyObject
    U:KeyObject
    V:KeyObject
    W:KeyObject
    X:KeyObject
    Y:KeyObject
    Z:KeyObject
    ENTER:KeyObject
    SHIFT:KeyObject
    ESC:KeyObject
    SPACE:KeyObject
    LEFT:KeyObject
    UP:KeyObject
    RIGHT:KeyObject
    DOWN:KeyObject
    BACKSPACE:KeyObject
    DELETE:KeyObject
    TAB:KeyObject
    TILDE:KeyObject
    CTRL:KeyObject
  }
}

不幸的是,这在实现中引发了一个错误: 'KD' only refers to a type, but is being used as a value here. [2693]

1 个答案:

答案 0 :(得分:1)

打字稿模块可以导出值类型。因此,当您说export default interface时,就是在声明导出的类型

相反,您想声明模块导出一个 value 。为此,在模块声明中添加const并将其设置为默认导出。

const defaultExport: KD
export default defaultExport

export interface KD { ... } // removed "default"