简体   繁体   English

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

[英]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 ! 谢谢 !

Update 更新

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.

相关问题 TypeScript为“ as X”定义接口 - TypeScript define interface for “as X” 如何在Typescript接口中为函数定义void的返回类型? - How can I define a return type of void for a function in a Typescript interface? 如何在 TypeScript 中为我的常量定义接口或类型? - How can I define an interface or type in TypeScript for my constant? 如何在导出的Typescript类中定义接口? - How can I define an interface in an exported Typescript class? 我可以定义一个带有计算键的 Typescript 接口吗? - Can I define a Typescript interface with computed keys? 如何在TypeScript中定义Decorator接口 - How can you define a Decorator interface in TypeScript 我可以为类的方法定义通用的打字稿接口吗? - Can I define a generic typescript Interface for the methods of a Class? 为什么我不能在打字稿类中定义接口或类型 - why i can't define interface or type inside typescript class 在 Typescript 中,如何定义一个 class 接口,其中包含一个属性成员,该属性成员是可区分的联合类型? - In Typescript, how can I define a class interface containing a property member that is a discriminated union type? 如何定义正确的地图 <X,Y> 输入打字稿,其中Y将是Parent的任何子类? - How to define correct Map<X,Y> type in typescript where Y will be any child class of Parent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM