简体   繁体   English

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

[英]How to create typescript declaration for object literal npm module export?

I need to make a .d.ts file for a npm module I have this npm module https://github.com/jeremyckahn/keydrown I am writing keydrown.d.ts我需要为 npm 模块制作一个.d.ts文件我有这个 npm 模块https://github.com/jeremyckahn/keydronn I am writing keydrown.d.ts

It has a weird interface:它有一个奇怪的界面:

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

My current .d.ts file looks like:我当前的.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
  }
}

Unfortunately this throws an error in the implementation: 'KD' only refers to a type, but is being used as a value here. [2693]不幸的是,这会在实现中引发错误: 'KD' only refers to a type, but is being used as a value here. [2693] 'KD' only refers to a type, but is being used as a value here. [2693]

A typescript module can export both values and types.打字稿模块可以导出值类型。 So when you say export default interface you are declaring a type that is exported.因此,当您说export default interface您是在声明导出的类型

Instead, you want to declare that the module exports a value .相反,您要声明该模块导出一个value To do that add a const to your module declaration and set that as the default export.为此,请在模块声明中添加一个const并将其设置为默认导出。

const defaultExport: KD
export default defaultExport

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM