通过Object.assign在Typescript类中扩展`this` [英] Extending `this` in Typescript class by Object.assign
问题描述
我有一个对象remote
,它本身不是类实例.由于Angular 2-5的性质,我需要将此对象包装在服务中,以便将其注入组件中.该对象的接口声明为"Remote
".
I have an object remote
which is not a class instance itself. Due to the nature of Angular 2-5 I need to wrap this Object in a service so I can inject it into components. The object has an interface declared 'Remote
'.
我将如何进行以下工作?
How would I make the following work?
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
本身不是类的实例,而只是对象.
I.e., how do I make a service class RemoteService
which instances look like Remote
, without having to manually wrap all remote
's members? I cannot use extend because remote
is not itself an instance of a class, just an object.
在上面的示例中,Typescript编译器将抱怨<c2>错误地实现了Remote
(自然).有什么方法可以迫使编译器将RemoteService
理解为实现Remote
?
In the example above the Typescript compiler will complain that RemoteService
incorrectly implements Remote
(naturally). Is there any way to coerce the compiler into understand RemoteService
as implementing Remote
?
推荐答案
TypeScript类应使用接口进行扩充.这导致合并的声明断言实现了Remote
方法:
TypeScript class should be augmented with an interface. This results in merged declaration that asserts that Remote
methods are implemented:
import { remote, Remote } from 'electron';
export interface RemoteService extends Remote {}
@Injectable()
export class RemoteService implements Remote {
constructor() {
Object.assign(this, remote);
}
}
Object.assign
仅在属性为常数且方法是拥有且可枚举的情况下才能正常工作.
Object.assign
will only work properly if properties are constant, and methods are own and enumerable.
为了更有效的继承,可以创建基类以提供原型链:
For more efficient inheritance, base class can be created in order to provide prototype chain:
import { remote, Remote } from 'electron';
export interface BaseRemote extends Remote {}
export class BaseRemote implements Remote {}
BaseRemote.prototype = remote;
@Injectable()
export class RemoteService extends BaseRemote {
/* custom methods */
}
如果类扩展了对this
上下文具有限制的奇异对象(请参见例如带有原生sessionStorage
对象的示例,或者绑定了对象方法,则应以任何方式为原始方法提供包装方法.如果包装器方法是通过编程方式创建的(通过使用for..in
等遍历属性),而不是通过class
语法创建的,则应该另外使用合并的声明来进行正确的键入.
If a class extends an exotic object that has restrictions on this
context (see the example with native sessionStorage
object), or object methods were bound, wrapper methods should be provided for original methods any way. If wrapper methods are created programmatically (by iterating over properties with for..in
, etc) and not through class
syntax, merged declaration should be additionally used for proper typing.
这篇关于通过Object.assign在Typescript类中扩展`this`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!