繁体   English   中英

如何在打字稿中以xy形式定义接口?

[英]How can i define interface in x.y form in typescript?

我想扩展我的库的原型,而库正在用JavaScript编写。

就像我有一个模块X ,以及一个Y类。

我想要的是通过以下方式扩展Y

X.Y.prototype.method = function() { ... }

这将在纯JavaScript中工作,但在打字稿中,它将引发错误。 看来我需要通过以下方式为Y模块添加接口:

interface X.Y {
    method(): any
}

但是,它引发以下错误:

error TS1005: '{' expected.
error TS1005: ';' expected.

我对此一无所知...任何人都可以帮助我吗? 谢谢 !

更新

这是一个最小的演示:

// index.html
<!doctype html>
<html>
    <head>
        <script src="./x.js"></script>
    </head>
    <body>
        <script src="./app.js"></script>
    </body>
</html>


// x.js
var x = {
    y: function() { }
}

// x.d.ts
declare module x {
    export class y {}
}

// app.ts
interface x.y {
  test: () => void
}

x.y.prototype.test = function() {

}

大概这样会有所帮助

// let's pretend this is our original lib
const X = function () { };


type ExtendedProto = {
  new (): {
    test: (arg1: string) => void;
  }
};

const Y = X as typeof X & ExtendedProto;

Y.prototype.test = function(arg1: string) {
  // console.log('test');
}

const y = new Y();
y.test('1');

或者您可以使用以下内容创建一个index.d.ts文件

// index.d.ts
declare module 'x-y-z' {
  export class X {}
}

// .ts file
import { X } from 'x-y-z';

class Y extends X {
   test() { console.log('test'); }
}

const y = new Y();
y.test();

暂无
暂无

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

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