Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
905 views
in Technique[技术] by (71.8m points)

exporting enum from typescript type definition file

I'm writing the type definitions for a library I'm using. One function in the library identifies the mouse button clicked by an integer:

 //index.d.ts
 export as namespace myLib;
 // activates the library listening for a specific mouse button
 function activate(button : number ) : void 

I introduced an enum to make this nicer:

//index.d.ts
export as namespace myLib;
export enum MouseButton {
    LEFT = 1,
    MIDDLE = 2,
    RIGHT = 4
}

export function activate(button : MouseButton ) : void;

Now, when I import this function and use it, everything compiles but I guess the enum is stripped and undefined when executed in the browser. The error message says Cannot read property 'LEFT' of undefined.

Therefore I rearranged the files like so:

//MouseButton.ts
export enum MouseButton {
    LEFT = 1,
    MIDDLE = 2,
    RIGHT = 4
}

//index.d.ts
export as namespace myLib;
import {MouseButton} from MouseButton;
export {MouseButton} from MouseButton;
export function activate(button : MouseButton ) : void;

Now I can import {MouseButton} from "myLib/MouseButton"; import * as myLib from "myLib". But this requires two imports. Referencing myLib.MouseButton still compiles but doesn't run.

Is there any way to import and reference the MouseButton enum via the myLib imported via the import * as myLib statement? I'm not only looking for an answer explaining how to do it but for one explaining why my solution doesn't work or why it isn't possible. Hints to resources explaining what's wrong are also appreciated

PS: I also tried the syntax suggested here re-export Typescript enum from namespace? but that didn't work either.

PPS: The module in question is a UMD module from the cornerstone project (https://github.com/cornerstonejs/cornerstone) used in an angular 6 project.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

(To complete t.animal's own answer)

Declaration files are difficult to make: see the long documentation. Sometimes looking in existing .d.ts files can help.

Regarding enum, declaring them as const enum is a clean and simple approach. It's what is done for jquery for instance, see @types/jquery/index.d.ts for Mouse and Key. It's handy because standard enums are compiled in JavaScript as arrays while const enum members are compiled directly as values ; see TypeScript Playground.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...