簡體   English   中英

TypeScript 0.9.1 CommonJS:正確聲明實現外部接口的導出環境類?

[英]TypeScript 0.9.1 CommonJS: correctly declaring exported ambient class implementing external interface?

編輯:

換句話說.d.ts文件中的以下內容不應該產生編譯器錯誤TS2137'類“MyClass”沒有實現接口“IInterface”':

interface IInterface {
    someMethod():void;
}
declare module "mod" {
    export class MyClass implements IInterface {
        constructor();
    }
}

因為我不是(也不能在聲明中)實施任何東西。 這是編譯器中的錯誤還是有其他方法/語法來執行上述含義? 我認為編譯器足夠聰明,可以准確地將IInterface的簽名作為MyClass的一部分包含在內,並且不需要重新聲明其方法。

原版的:

我正在嘗試為節點組件bunyan寫一個d.ts。 導出實現外部接口的類時遇到問題,特別是擴展節點的EventEmitter的RingBuffer。 簡化的問題是(在bunyan.d.ts文件中):

// this interface declared in <reference..., put inline here for simplicity
interface IExternal {
    inheritedMethod():void;
}

interface RingBuffer extends IExternal {
    write():void;
}
declare var RingBuffer: {
    new():RingBuffer;
}

declare module "bunyan" {
    export var RingBuffer;
}

然后在myNodeApp.js中使用

/// <references path="bunyan.d.ts" />

import bunyan = require( 'bunyan' );
var rb = new bunyan.RingBuffer();

// compiler doesn't error on this; thinks RingBuffer is type any.
// also, no intellisense to show write() method.
rb.badFunc();

將bunyan.d.ts更改為:

declare module "bunyan" {
    export class RingBuffer { constructor(); }
}

編譯,但使用時同樣的問題; 沒有intellisense,沒有編譯錯誤。


將bunyan.d.ts改為

declare module "bunyan" {
    export var RingBuffer:RingBuffer;
}

導致myNodeApp.js中的編譯錯誤

// error TS2083: Invalid 'new' expression
import rb = new bunyan.RingBuffer();

從bunyan.d.ts刪除

declare module "bunyan" {
    ...
}

導致myNodeApp.js中的編譯錯誤

// error TS2071: Unable to resolve external module ''bunyan''
import bunyan = require( 'bunyan' );

改變bunyan.d.ts

interface IExternal {
    inheritedMethod():void;
}
interface IRingBuffer extends IExternal {
}

declare module "bunyan" {
    export class RingBuffer implements IRingBuffer {}
}

導致編譯錯誤

// error TS2137: Class "bunyan".RingBuffer declares interface IRingBuffer but 
// does not implement it: type '"bunyan".RingBuffer' is missing property
// 'inheritedMethod' from type 'IRingBuffer'

暗示我必須從所有擴展接口重新聲明所有繼承的方法,除了IRingBuffer,這在d.ts文件中似乎有點荒謬

有沒有人知道聲明一個環境類的“正確”方法,該環境類實現了在另一個CommonJS模塊中使用的接口?

定義它的另一種方法是定義Jquery的typescript定義。 您有靜態和實例成員的單獨接口。 以下是完整定義示例:

interface IExternal {
    inheritedMethod():void;
}

interface IRingBuffer extends IExternal {
    write():void;
}
// Static functions and constructors 
interface IRingBufferStatic{
    new():IRingBuffer;  
}
declare var RingBuffer:IRingBufferStatic;

declare module "bunyan" {
    export var RingBuffer:IRingBufferStatic;
}

// In the second file 

import bunyan = require( 'bunyan' );
var rb = new bunyan.RingBuffer();

// you get an error here 
rb.badFunc();

在線嘗試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM