Assigning Typescript Designer Parameters

I have an interface:

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

And I have a 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 post I was thinking about refactoring:

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

Question: In the first class, I have fields that should be like by default private. In the second example, I can install them only as public. Is this all right, or is my understanding of the default access modifiers in TypeScript?

+4
source share
1 answer

Default. TypeScript Documentation

In the 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>.valuepublicly accessible by default.

since they are here

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

:. , this.name this.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) {}
}

, , , .

+11

Source: https://habr.com/ru/post/1668193/


All Articles