分配 Typescript 构造函数参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41923069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:12:49  来源:igfitidea点击:

Assigning Typescript constructor parameters

typescriptaccess-modifiers

提问by demo

I have interface :

我有接口:

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

And I have class that implements it :

我有实现它的类:

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

after reading this postI've thinking about refactoring :

阅读完这篇文章后,我开始考虑重构:

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

Question : In first class I have fields which by default should be as private. In second sample I can only set them as public. Is it all correct or my understanding of default Access modifiers in TypeScript?

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

回答by Maciej Caputa

Public by default. TypeScript Documentation

默认公开。 打字稿文档

In following definition

在以下定义中

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

Attributes <Person>.nameand <Person>.valueare public by default.

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

as they are here

因为他们在这里

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

Beware:Here is an incorrect way of doing it, since this.nameand this.valuewill be regarded as not defined in the constructor.

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

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

To make these attributes private you need to rewrite it as

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

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

or equivalently

或等效地

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

which in my opinion is the most preferable way that avoids redundancy.

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