Immutable parameter in constructor

While analyzing some TypeScript code, I stumbled upon a peculiar declaration within a class definition:

constructor(readonly constructorParam : Type) {
  // no assignment of constructorParam here
}

Surprisingly, constructorParam is still being used as usual.

Could it be that the constructorParam property is automatically "created and assigned"?

This class is also wrapped in

export abstract class ... extends ... implements ...
(where extends and implement are standard inheritance keywords, and export is typically used for module management).

LATEST UPDATE

After reading through this article, it appears that indeed, constructor parameters marked as readonly are treated in this manner - creating and assigning values by default.

Answer №1

As mentioned in this particular article, there is a convenient shorthand for declaring all class properties as constructor parameters, such as:

constructor ( public someProp : number )

When utilizing this syntax, the property someProp will be initialized. This declaration is comprehensive, including type definition (number in this scenario), access modifiers, and more. Instead of public, other keywords like private readonly can also be used.

Answer №2

One possible approach is as follows:

constructor(private readonly parameter : Type = "Default") {
  // in this scenario, the parameter is not assigned any value
}

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

Error: In Angular Firebase, the type 'string' cannot be assigned to the type 'Date'

I am encountering an error. The following error is shown: "cannot read property 'toDate' of undefined. Without the toDate() | Date." After further investigation, I found: A Timestamp object with seconds=1545109200 and nanoseconds=0. A hel ...

I am looking to extract only the alphanumeric string that represents the Id from a MongoDB query

Working with mongoDB, mongoose, and typescript, I am facing an issue where I need to preserve the document ids when querying. However, all I can retrieve is the type _id: new ObjectId("62aa4bddae588fb13e8df552"). What I really require is just the string ...

Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below: @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) expo ...

"In TypeScript, when something is undefined, it means its value

I am currently working on a class with code to help manage a database. export class DatabaseHelper { public browserID : number; private ConfigID = 17; } Within this class, I am attempting to access the value of ConfigID SetBrowserID() { ...

adjusting the scrollbar to be positioned at the top when using Material UI stepper component

While using the material ui stepper, I encountered an issue where the scroll bar remains static and hidden behind the step number header when I click on the "save and continue" button. I expect that upon clicking the button, the scroll bar should automatic ...

Structuring your Angular 6 application and server project

What is the recommended project structure when developing an Angular 6 application and an API server that need to share type definitions? For example: On the client side: this.httpService.get<Hero[]>(apiUrl + '/heroes') On the server si ...

An unexpected error has occurred: Uncaught promise rejection with the following message: Assertion error detected - The type provided is not a ComponentType and does not contain the 'ɵcmp' property

I encountered an issue in my Angular app where a link was directing to an external URL. When clicking on that link, I received the following error message in the console: ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: Type passed in is not Co ...

Secure higher order React component above class components and stateless functional components

I have been working on creating a higher order component to verify the authentication status of a user. Currently, I am using React 15.5.4 and @types/react 15.0.21, and below is a simplified version of my code: import * as React from 'react'; i ...

Encountering issues with deploying an Angular 8 website using a specific configuration

My current project is built on Angular 8, and I am in the process of publishing it locally before deploying it. When running the build step, I specify an environment name called internalprod: src ├───app ├───environments │ environme ...

Angular EventEmitter coupled with Callbacks

In order to create a custom button component for my angular application and implement a method for click functionality, I have the following code snippet: export class MyButtonComponent { @Input() active: boolean = false; @Output() btnClick: EventEmit ...

Tips for crafting a TypeScript function signature for a bijection-generating function

One of my functions involves taking a map and generating the bijection of that map: export function createBijection(map) { const bijection = {}; Object.keys(map).forEach(key => { bijection[key] = map[key]; bijection[map[key]] = key; }); ...

What is the best way to retrieve the current height in VueJS using the Composition API?

I am utilizing a Ref to preserve the current height of the active element. My goal now is to transfer this height to the subsequent element that gets clicked on. <script lang="ts" setup> import { ref, reactive } from "vue"; defin ...

Utilizing TypeScript to enhance method proxying

I'm currently in the process of converting my JavaScript project to TypeScript, but I've hit a roadblock with an unresolved TypeScript error (TS2339). Within my code base, I have a class defined like this: export const devtoolsBackgroundScriptCl ...

Tips for creating a sophisticated state transition diagram using Typescript

If you have a creative idea for a new title, feel free to make changes! I have two enums set up like this: enum State { A = "A", B = "B", C = "C" } enum Event { X = "X", Y = "Y", Z ...

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

The never-ending cycle of an Angular dropdown linked to a function being repeatedly invoked

I am currently working with a PrimeNg dropdown that is fetching its options through a function call. However, I have noticed that this function is being called an excessive number of times. Could this potentially impact the performance or any other aspect? ...

What is the reason behind being unable to register two components with the same name using React Hook Form?

I have encountered an issue while using the useForm hook from React Hook Form library. Due to the specific UI library I am using, I had to create custom radio buttons. The problem arises when I try to register two components with the same name in the form ...

Obtaining the attribute value from a custom tag in Angular: A comprehensive guide

I am currently working on creating a customized password component in Angular5. I am having difficulty obtaining the minimum and maximum attribute values required to validate the password. I attempted to retrieve the values using JavaScript's getAttr ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...

Guide to configure Validator to reject the selection of the first index option in Angular 2

When using a select option, it should be set up like: <div class="form-group row" [ngClass]="{'has-error': (!form.controls['blockFirstIndex'].valid && form.controls['blockFirstIndex'].touched), 'has-success&ap ...