【问题标题】:can a typescript call implement an interface, and make the vars private?打字稿调用可以实现一个接口,并使变量私有吗?
【发布时间】:2014-07-12 02:49:02
【问题描述】:

这就是我想要做的。我们以类的结构接收 JSON 数据。所以我们可以这样声明一个接口:

export interface IElement {
id : number;
name : string;
}

然后类如下:

export class Element implements IElement {
    id : number;
    name : string;

constructor (src : IElement) {
    this.id = src.id;
    this.name = src.name;
    }
}

然后我们将 JSON 数据转换为 并将其传递给类构造函数。然后可以向构造函数传递一个 IElement 或一个 Element 并且生活很好。

但是...我想强制访问使用 getter 和 setter。所以我想做的是:

export class Element implements IElement {
    private id : number;
    private name : string;

constructor (src : IElement) {
    this.id = src.id;
    this.name = src.name;
    }

getId () : number {
    return this.id;
    }
getName () : string{
    return this.name;
    }
}

以上对我来说仍然可以正常工作,因为在构造函数中我被允许访问这些变量。但是,如果将它们设置为私有,则 Element 将不再实现 IElement,因为它不履行 IElement 中的约定。

有没有办法做到这一点?如果必须,Element 不必实现 IElement,但如果它实现了,它会让生活更整洁。

【问题讨论】:

    标签: interface typescript


    【解决方案1】:

    您的公共表面区域可以替代界面,或者不能。该类不能替代IElement(如果你想强制人们使用getter,它不应该!),所以它不能implement 接口。

    由于您没有说明为什么希望人们使用 getter,我不知道这是否合适,但您可以在类中使用属​​性 getter:

    export interface IElement {
        id: number;
        name: string;
    }
    
    export class Element implements IElement {
        private _id: number;
        private _name: string;
        constructor (src: IElement) {
            this._id = src.id;
            this._name = src.name;
        }
    
        get id() {
            return this._id;
        }
    
        get name() {
            return this._name;
        }
    }
    

    【讨论】:

    • 谢谢,是的,这正是我所需要的。
    • 这是唯一的解决方法。我看到如果我不注入 src: IElement 它会出错。有没有办法做这样的事情>>export interface IElement { private id : number; private name : string; }
    猜你喜欢
    • 2016-06-08
    • 2017-08-31
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多