[英]How can i define interface in x.y form in typescript?
I want to extend my lib's prototype, and the lib is writing by JavaScript. 我想扩展我的库的原型,而库正在用JavaScript编写。
Just like I have a module X
, and a Y
class under it. 就像我有一个模块
X
,以及一个Y
类。
What I want is to extends Y
by: 我想要的是通过以下方式扩展
Y
:
X.Y.prototype.method = function() { ... }
This will work in pure JavaScript, but in typescript, it throw error. 这将在纯JavaScript中工作,但在打字稿中,它将引发错误。 It seems I need to add interface for the
Y
module by: 看来我需要通过以下方式为
Y
模块添加接口:
interface X.Y {
method(): any
}
However, it throw the following error: 但是,它引发以下错误:
error TS1005: '{' expected.
error TS1005: ';' expected.
I have no idea about this... Can anyone help me ? 我对此一无所知...任何人都可以帮助我吗? Thanks !
谢谢 !
Here is a minimal demo: 这是一个最小的演示:
// 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() {
}
Probably something like this will help 大概这样会有所帮助
// 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');
or you could creating an index.d.ts file with approximately the following 或者您可以使用以下内容创建一个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.