我有一个对象remote,它本身不是类实例。由于角度2-5的性质,我需要将这个对象包装在一个服务中,这样我就可以将它注入组件中。对象有一个声明为'Remote‘的接口。
我将如何做以下工作?
import { Injectable } from '@angular/core';
import { remote, Remote } from 'electron';
@Injectable()
export class RemoteService implements Remote {
constructor() {
Object.assign(this, remote);
}
}例如,如何使一个实例看起来类似于RemoteService的服务类Remote,而不必手动包装所有remote的成员?我不能使用扩展,因为remote本身不是类的实例,而只是一个对象。
在上面的例子中,类型记录编译器会抱怨RemoteService不正确地实现Remote (自然)。有没有办法强迫编译器将RemoteService理解为实现Remote?
发布于 2018-01-29 07:12:30
TypeScript类应该使用接口进行扩展。这将导致合并声明,声明实现了Remote方法:
import { remote, Remote } from 'electron';
export interface RemoteService extends Remote {}
@Injectable()
export class RemoteService implements Remote {
constructor() {
Object.assign(this, remote);
}
}只有在属性是常量且方法是自己的和可枚举的情况下,Object.assign才能正常工作。
为了更有效地继承,可以创建基类以提供原型链:
import { remote, Remote } from 'electron';
export interface BaseRemote extends Remote {}
export class BaseRemote implements Remote {}
Object.setPrototypeOf(BaseRemote.prototype, remote);
// or
/*
export const BaseRemote = function BaseRemote() {} as Function as { new(): Remote };
BaseRemote.prototype = remote;
*/
@Injectable()
export class RemoteService extends BaseRemote {
/* custom methods */
}如果类扩展了对this上下文有限制的外来对象(参见 object),或者绑定了对象方法,则应该以任何方式为原始方法提供包装器方法。如果包装器方法是以编程方式创建的(通过使用for..in等迭代属性,而不是通过class语法创建),则还应该使用合并声明来进行正确的键入。
https://stackoverflow.com/questions/48495665
复制相似问题