如何在TypeScript声明源文件中声明嵌套函数?

时间:2013-01-16 22:55:28

标签: javascript typescript

我正在为KeyboardJS构建声明源文件。 API是从加载JavaScript文件时实例化的静态对象(KeyboardJS)引用的。 API的一些方法嵌套在其他方法下。例如:

KeyboardJS.clear(keyCombo);

KeyboardJS.clear.key(key);

这是我的界面定义:

interface KeyboardJSStatic {
    enable(): void;
    disable(): void;
    activeKeys(): string[];
    on(keyCombo:string, onDownCallback?: (keyEvent: Event, keysPressed: string[], keyCombo: string) => {}, onUpCallback?: (keyEvent: Event, keysPressed: string[], keyCombo: string) => {}): KeyboardJSBinding;
    clear(keyCombo: string): void;
    clear.key(keyName: string): void;
    locale(localeName: string): KeyboardJSLocale;
    locale.register(localeName: string, localeDefinition: KeyboardJSLocale): void;
    macro(keyCombo:string , keyNames: string[]): void;
    macro.remove(keyCombo: string): void;
    key: KeyboardJSKey;
    combo: KeyboardJSCombo; 
}

Visual Studio 2012的TypeScript插件在clear.key行上生成并出错,建议使用分号表示句点的位置。有没有人用类似的场景构建定义文件?谢谢!

2 个答案:

答案 0 :(得分:8)

您可以在以下类型上声明呼叫签名:

interface KeyboardJSStatic {
    // ...
    clear: {
        (keyCombo: string): void; // Call signature
        key(keyName: string): void; // Method
    };
    // ...
}

var n: KeyboardJSStatic;
n.clear('a'); // OK
n.clear.key('b'); // OK

答案 1 :(得分:2)

Ryan的天才评论。使用与jQuery定义相同的模式:

interface KeyboardJSClear {
    (keyCombo: string) : void;
    key(keyName: string): void;
}

interface KeyboardJSLocale {
    (localeName: string) : KeyboardJSLocale;
    register(localeName: string, localeDefinition: KeyboardJSLocale): void;
}

interface KeyboardJSMacro {
    (keyCombo:string , keyNames: string[]): void;
    remove(keyCombo: string): void;
}

interface KeyboardJSStatic {
    enable(): void;
    disable(): void;
    activeKeys(): string[];
    on(keyCombo:string, onDownCallback?: (keyEvent: Event, keysPressed: string[], keyCombo: string) => {}, onUpCallback?: (keyEvent: Event, keysPressed: string[], keyCombo: string) => {}): KeyboardJSBinding;
    clear: KeyboardJSClear;
    locale: KeyboardJSLocale;
    macro: KeyboardJSMacro;
    key: KeyboardJSKey;
    combo: KeyboardJSCombo; 
}

declare var KeyboardJS: KeyboardJSStatic;

KeyboardJS.clear('');
KeyboardJS.clear.key('');