首页 > 解决方案 > 覆盖 Typescript 中一组属性的 getter

问题描述

我想做类似以下的事情:

class Properties {
    a = 12;
    b = false;
    c = 'green';
}

@Injectable()
class PropertyService {
    private _properties: Properties;

    constructor(props: Properties) {
        this._properties = props;
    }

    // À la Python...
    __get__(propname): any {
        if (Object.prototype.hasOwnProperty(this._properties, propname)) {
            return this._properties[propname];
        }

        return undefined;
    }
}

目标是能够将其用作库中的服务,以便应用程序可以执行以下操作:

import { appProperties } from './config/properties';
...
    constructor(private props: PropertyService) {
        props.set(appProperties);
    }

而且,在图书馆中,我可以执行以下操作:

    constructor(private props: PropertyService) { }

    someMethod() {
        if (this.props.b) {
            ...
        }
    }

据我所知,getter 在 Typescript 中必须是特定于属性的。我在这里吠错树了吗?

标签: typescript

解决方案


推荐阅读