外部类实现我的界面?

时间:2018-04-09 14:07:33

标签: node.js typescript npm

有没有人知道将外部类(NPM模块的一部分)声明为实现某个接口的类的方法?

例如:

import {someClass} from "someNPMmodule";

interface myInterface {
  foo: () => void
}

现在我想强制someClass实现myInterface,然后将foo添加到原型中:

someClass["foo"] = function() { ... }

如何强制someClass实现myInterface?如果不将foo方法添加到someClass的原型中,我想要弹出编译错误。

实现这一目标的最佳方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

你可以这样试试:

export function foo = function() { ... };

someClass.prototype.foo = foo;

declare module 'someNPMmodule' {
    export interface someClass {
        foo: typeof foo;
    }
}

此代码增加了导入的模块。模块的名称必须与导入中使用的名称相同,包括路径:

我的意思是,如果你有:

import { someClass } from '@author/library'

然后您必须将模块定义为

declare module '@author/library';

接下来,在模块内部声明一个与要扩展的类同名的接口,并为其添加属性定义。现在,在该模块声明之外,您可以向someClass的原型添加一个新方法,TypeScript将识别它。

修改

如果你在另一个界面中定义了方法,就像你的情况一样,你也可以这样做:

export interface myInterface {
  foo: () => void
}

export function foo = function() { ... };
someClass.prototype.foo = foo;

declare module 'someNPMmodule' {
    export interface someClass extends myInterface { }
}

无论如何,仅仅为了记录,在TypeScript中实现接口意味着只具有相同类型的相同属性,因为TypeScript使用结构类型。

这意味着:

interface A { foo: () => void }

class AImp implements A {
    foo() { console.log(''); }
}

class BImp {
    foo() { console.log(''); }
}

const arr: A[] = [];

arr.push(new AImp());
arr.push(new BImp());

这很有效,即使BImp没有明确指出它实现了接口。这是因为界面只是说符合它的对象必须有foo类型为() => void的方法。 BImp有这样一种方法,因此它会影响界面。

同样,在我的第一个示例中,someClass也会通过声明其方法来实现myInterface

如果您对此解决方案有疑问,请发表评论。