首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Object.assign在类型记录类中扩展“`this`”

用Object.assign在类型记录类中扩展“`this`”
EN

Stack Overflow用户
提问于 2018-01-29 06:39:37
回答 1查看 2.5K关注 0票数 5

我有一个对象remote,它本身不是类实例。由于角度2-5的性质,我需要将这个对象包装在一个服务中,这样我就可以将它注入组件中。对象有一个声明为'Remote‘的接口。

我将如何做以下工作?

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-29 07:12:30

TypeScript类应该使用接口进行扩展。这将导致合并声明,声明实现了Remote方法:

代码语言:javascript
复制
import { remote, Remote } from 'electron';

export interface RemoteService extends Remote {}

@Injectable()
export class RemoteService implements Remote {
    constructor() {
        Object.assign(this, remote);
    }
}

只有在属性是常量且方法是自己的和可枚举的情况下,Object.assign才能正常工作。

为了更有效地继承,可以创建基类以提供原型链:

代码语言:javascript
复制
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语法创建),则还应该使用合并声明来进行正确的键入。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48495665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档