如何在typescript中以x.y格式定义接口?
我想扩展我的库的原型,库是用JavaScript编写的 就像我有一个模块如何在typescript中以x.y格式定义接口?,typescript,Typescript,我想扩展我的库的原型,库是用JavaScript编写的 就像我有一个模块X,下面有一个Y类一样 我想通过以下方式扩展Y: X.Y.prototype.method = function() { ... } 这将在纯JavaScript中工作,但在typescript中,它会抛出错误。似乎我需要通过以下方式为Y模块添加接口: interface X.Y { method(): any } 但是,它会抛出以下错误: error TS1005: '{' expected. error TS
X
,下面有一个Y
类一样
我想通过以下方式扩展Y
:
X.Y.prototype.method = function() { ... }
这将在纯JavaScript中工作,但在typescript中,它会抛出错误。似乎我需要通过以下方式为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() {
}
//index.html
//x.js
变量x={
y:函数(){}
}
//x.d.ts
声明模块x{
导出类y{}
}
//app.ts
接口x.y{
测试:()=>无效
}
x、 y.prototype.test=函数(){
}
像这样的东西可能会有所帮助
// 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();
发布一个完整的复制问题的最低限度的例子。但是你已经为你的图书馆打字了吗?TS可以帮助您扩展打字,但不能扩展实际的原型或其他类型objects@DanielKhoroshko为什么不能呢?因为在你将typescript转换成javascript之后,就不会留下任何痕迹了:-)它会执行所谓的静态类型,这意味着它允许你的开发环境了解更多关于你应用程序中类型的信息,仅此而已。其他一切都只是普通的javascript:原型、函数、类等等on@DanielKhoroshko他发布的js代码在js中运行良好。他所需要做的就是告诉编译器新方法已经添加到接口中了。