简体   繁体   中英

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.

Just like I have a module X , and a Y class under it.

What I want is to extends Y by:

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

This will work in pure JavaScript, but in typescript, it throw error. It seems I need to add interface for the Y module by:

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
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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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