Assigning Typescript constructor parameters

后端 未结 1 1844
隐瞒了意图╮
隐瞒了意图╮ 2021-02-07 08:56

I have interface:

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

And I have a class that implements it:

cla         


        
相关标签:
1条回答
  • 2021-02-07 09:34

    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>.name and <Person>.value are public by default.

    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.name and this.value will be regarded as not defined in the constructor.

    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.

    0 讨论(0)
提交回复
热议问题