【问题标题】:Assigning Typescript constructor parameters分配 Typescript 构造函数参数
【发布时间】:2017-06-14 20:27:40
【问题描述】:

我有接口:

export interface IFieldValue {
    name: string;
    value: string;
}

我有一个实现它的类:

class Person implements IFieldValue{
    name: string;
    value: string;
    constructor (name: string, value: string) {
        this.name = name;
        this.value = value;
    }
}

看了this post之后,我正在考虑重构:

class Person implements IFieldValue{
    constructor(public name: string, public value: string) {
    }
}

问题:在头等舱中,我的字段默认应为private。在第二个示例中,我只能将它们设置为 public。我对 TypeScript 中默认访问修饰符的理解是否正确?

【问题讨论】:

    标签: typescript access-modifiers


    【解决方案1】:

    默认公开。 TypeScript Documentation

    如下定义

    class Person implements IFieldValue{
        name: string;
        value: string;
        constructor (name: string, value: string) {
            this.name = name;
            this.value = value;
        }
    }
    

    <Person>.name<Person>.value 属性默认是公开的。

    他们在这里

    class Person implements IFieldValue{
        constructor(public name: string, public value: string) {
            this.name = name;
            this.value = value;
        }
    }
    

    注意:这是不正确的做法,因为this.namethis.value 将被视为未在构造函数中定义。

    class Person implements IFieldValue{
        constructor(name: string, value: string) {
            this.name = name;
            this.value = value;
        }
    }
    

    要将这些属性设为私有,您需要将其重写为

    class Person implements IFieldValue{
        private name: string;
        private value: string;
        constructor (name: string, value: string) {
            this.name = name;
            this.value = value;
        }
    }
    

    或等效

    class Person implements IFieldValue{
        constructor (private name: string, private value: string) {}
    }
    

    对于 TypeScript 2.X,由于接口具有公开的属性,您需要将 private 更改为 public 以及 export

    export class Person implements IFieldValue{
        constructor (public name: string, public value: string) {}
    }
    

    在我看来,这是避免冗余的最可取的方式。

    【讨论】:

    • 如果 Person 实现具有公共属性“名称”和“值”的 IFieldValue,则 namevalue 必须在 Person 类中保留 public。您提供的两个代码示例无法使用 TypeScript 2.x 进行编译。您可以更改界面并将道具设为私有,或者您可以拥有私有道具personNamepersonValue,例如:class Person implements IFieldValue{ private personName: string; private personValue: string; constructor (public name: string, public value: string) { this.personName = name; this.personValue = value; } }
    • 对不起,忽略我所说的部分:“你要么更改界面并使道具私有”没有意义,因为道具仅在界面上公开
    • fwiw,我在处理我想声明private 的注入参数时猜错了。仍然像上面一样工作,但 @Inject 出现在 私有之前。 @Inject(MyType) private _myType: MyType,
    • @phil_lgr 我已经更新了答案,对 TypeScript 2.X 进行了重要说明
    猜你喜欢
    • 2016-06-03
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    相关资源
    最近更新 更多