[英]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.