Utilizing Typescript for constructor parameter assignments

Within my codebase, there exists an interface:

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

This interface is implemented by a class named Person:

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

Recently, I came across an interesting post that inspired me to refactor the implementation:

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

My question pertains to the default access modifiers in TypeScript - in the first implementation, the fields are implicitly set as private, while in the refactored version they are automatically set as public. Am I correct in assuming this understanding?

Answer №1

By default, the information is made public. View TypeScript Documentation

In this particular scenario

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

The attributes <Person>.name and <Person>.value are automatically set to public.

as seen in the following code snippet

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

Note: The incorrect way of approaching this would be by defining this.name and this.value within the constructor.

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

To keep these attributes private, a different implementation is required like so

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

or alternatively

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

For TypeScript 2.X, where the interface properties are public, changing from private to public and adding export to classes is necessary

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

This is considered the most efficient method that eliminates redundancy according to my personal opinion.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Translating from a higher-level programming language to a lower-level programming language

Is compilation effectively the transformation of high-level programming languages (HLL) into machine code or low-level language? If so, why is TypeScript (a HLL) compiled to JavaScript (also a HLL) instead of being compiled to a low-level language? ...

What is the best way to apply DateRange filtering in a Kendo Ui Grid?

Currently I am working with the Kendo Ui Grid and attempting to implement filtering by DateRange. Here is a snippet of my current code: HTML: <kendo-grid-column field="createdate" title="Creation Date" width="150"> <ng-template kendoGridFilterC ...

The specified module '...' is identified as a non-module entity and therefore cannot be imported using this specific construct

Currently, I am facing an issue in my .tsx file where I am attempting to import a RaisedButton component from material-ui using the following code: import * as RaisedButton from 'material-ui/lib/raised-button' Unfortunately, this is triggering ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

Upon transitioning from Angular 5 to Angular 6, a noticeable issue arises: The existing document lacks a required doctype

I recently updated my project from Angular 5 to Angular 6. Post-upgrade, everything compiles without errors. However, when I try to access the website, all I see is a blank screen. Upon inspecting the console, I came across the following error message: Th ...

Collaborative service utilization in Angular 2

My goal is to create a shared service for my app. import { Injectable } from '@angular/core'; @Injectable() export class SharedService { testService() { console.log('share!'); } } However, when I attempt to inject this shared ...

The ng-bootstrap typeahead is encountering an error: TypeError - Object(...) is not functioning correctly

Hey there! I'm trying to integrate the Angular Bootstrap typeahead component in my Angular 5 application by following the linkToTypeahead. However, I'm encountering some errors along the way. Here's what I'm seeing: ERROR TypeError: Ob ...

Show the user's chosen name in place of their actual identity during a chat

I'm facing an issue where I want to show the user's friendly name in a conversation, but it looks like the Message resource only returns the identity string as the message author. I attempted to retrieve the conversation participants, generate a ...

Determining the type of an overloaded method within a generic function

I am currently working on developing a versatile function that can subscribe to an event emitter. The function subscribe is designed to take 3 arguments: event name, event handler, and the event emitter to connect to. I am looking for ways to ensure accur ...

The error encountered is: "Unable to modify the 'x' property as it is readonly for the '[object Array]' object."

I've attempted various methods to modify this problem, regardless of how it's explained on different Stack Overflow threads. I am faced with an obstacle where I have an array composed of objects, and my goal is to iterate through the array and mo ...

Error encountered in Typescript while attempting to $set a subdocument key value in MongoDB

This is a sample data entry. { _id: ObjectId('63e501cc2054071132171098'), name: 'Ricky', discriminator: 7706, registerTime: ISODate('2023-02-09T14:23:08.159Z'), friends: { '63e502f4e196ec7c04c4 ...

Using `querySelector` in TypeScript with Vue 3

Encountered a TypeScript error while using the Vue Composition API let myElement = document.querySelectorAll('my-element') The TS error I'm getting when trying to access it like this: Property '_props' does not exist on type ...

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...

What are some effective ways to create a flexible framework in Typescript for Node.js applications utilizing the native MongoDB driver?

When using node.js and the native mongodb driver, is there a way to implement a schema/schemaless structure by utilizing classes or interfaces with Typescript (ES6)? For instance, if we have a collection named users and perform actions like ...

I am having trouble locating my source code within the Typescript module

My issue lies with a file called Server.js, which holds the code for export class Program and includes <reference path='mscorlib.ts'/>. However, when I compile it using the command: tsc -t ES5 Server.ts --module commonjs --out Server.js T ...

NodeJS can be used to convert JSON data into an XLSX file format and allow for

I am currently working on a project in nodejs where I need to convert JSON data into XLSX format and then download it to the client's browser. I have been using the XLSX npm module to successfully convert the JSON data into a Workbook, however, I am f ...

Utilizing a class structure to organize express.Router?

I've been playing around with using Express router and classes in Typescript to organize my routes. This is the approach I've taken so far. In the index.ts file, I'm trying to reference the Notes class from the notes.ts file, which has an en ...

Error Message: The Reference.update operation in Angular Firebase failed due to the presence of undefined value in the 'users.UID.email' property

Having recently started to use the Firebase database, I encountered an issue while trying to update the UID to the Realtime Database during signup. The error message displayed was: Error: Reference.update failed: First argument contains undefined in prop ...

Can you explain the distinction, if one exists, between a field value and a property within the context of TypeScript and Angular?

For this example, I am exploring two scenarios of a service that exposes an observable named test$. One case utilizes a getter to access the observable, while the other makes it available as a public field. Do these approaches have any practical distincti ...

Error in Visual Studio 2019 - TypeScript version discrepancy

I am completely puzzled by the mismatch in Typescript versions when using Visual Studio 2019 with my .NET Core 2.2.x project. Every time I make changes to a .ts file, I receive the following warning (found in the error list): Your project is built using ...