Ensure the proper sequence of field initialization within a TypeScript class constructor

Is there a way to ensure the proper initialization order of class fields in TypeScript (4.0) constructors?

In this example (run), this.x is accessed in the method initY before it's initialized in the constructor:

class A  {
  readonly x: number
  readonly y: number

  constructor(x: number){
    this.y = this.initY() // this.x not initialized yet
    this.x = x
  }

  private initY(): number {
    return this.x + 1
  }
}

console.log(new A(1).y) // prints: NaN

The solution I found involved using a static method or top-level function for initialization.

Any other more concise ideas? Can the compiler (already in strict mode) or linter catch these issues?

Answer №1

To ensure type safety, one approach is to declare members as nullable types and implement typeguards to verify before using variables that can be null.

This method involves declaring x and y as a union of number | null

class A  {
  readonly x: number | null
  readonly y: number | null

  constructor(x: number){
    this.y = this.initY() // x is not initialized yet
    this.x = x
  }

  private initY(): number {
    // Will not compile unless you check for null first
    return this.x + 1
  }
}

https://i.stack.imgur.com/usDmy.png

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

What are the steps for incorporating the AAD B2C functionality into an Angular2 application with TypeScript?

I recently built a web application using Angular2 and TypeScript, but now one of my clients wants to integrate Azure B2C for customer login instead of OAuth. I followed a simple example on how to implement Azure B2C in a .NET Web app through the link provi ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

The variable "theme" is referenced prior to being initialized

https://i.stack.imgur.com/QL0pa.png One of the variables in my code, theme, is set to be assigned a value from a for loop: let theme: Theme for (const themeObj of themeList) { const [muiThemeName, muiTheme] = Object.entries(themeObj)[0]!; if (muiThem ...

Creating a signature for a function that can accept multiple parameter types in TypeScript

I am facing a dilemma with the following code snippet: const func1 = (state: Interface1){ //some code } const func2 = (state: Interface2){ //some other code } const func3: (state: Interface1|Interface2){ //some other code } However, ...

Discovering an entry that lacks a specific value within an array in the records

Currently, I am utilizing sequelize along with typescript in a node environment (with a postgresql database). Here is the model that I have defined: id: number, someField: string, arr1: number[], arr2: number[] My objective is to retrieve all records wher ...

How Vue3 enables components to share props

Having recently made the switch from Vue2 to Vue3, I find myself a bit perplexed about the best approach for sharing props among multiple components. My goal is to create input components that can share common props such as "type", "name", and so on. Previ ...

Tips for saving a variable in Angular that is being received through a subscription as JSON:

Below is an example of the json I have: [{"id":"1","date":"2020-02-21","status":"present","studentid":"1"},{"id":"2","date":"2020-02-24","status":"present","studentid":"1"}] I am struggling to store the date in a variable using Angular when it is being s ...

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 ...

Matching the Expected Type with Custom SWR Hook's Return Type

Currently, I am working on integrating swr into my project to create a custom block hook using generics. The goal is to have this hook creator accept mapParamsToKey and request methods as parameters and generate an SWR hook function. However, there seems t ...

Incorporate keyboard input functionality into an object wrapper

Adding typing to a class that encapsulates objects and arrays has been a bit tricky. Typing was easily implemented for objects, but ran into issues with arrays. interface IObject1 { value1: string, } interface IObject2 { myObject: IObject1, ...

What steps can be taken to retrieve error.data from RTK Query while utilizing typescript?

When I log error to the console, this is what I see: { status: 401, data: "Invalid password" } If I attempt to log error.data, an error occurs: The "data" property does not exist in the "FetchBaseQueryError|SerializedErr ...

Transform the code provided by bundleMDX into an HTML string specifically for RSS, all the while utilizing the mdx-bundler

I am currently working on developing an RSS reader and I need to convert the code returned by bundleMDX into a string. This is necessary so that I can utilize it with ReactDOMServer.renderToStaticMarkup(mdx) in my project. You can find a similar implement ...

The static side of the class `typeof _Readable` is erroneously extending the static side of the base class `typeof Readable`

I am currently developing a Discord bot using node/typescript. After running the typescript compiler on my code, I encountered this error: node_modules/@types/readable-stream/index.d.ts(13,15): error TS2417: Class static side 'typeof _Readable' ...

Erase Typescript Service

To remove a PostOffice from the array based on its ID, you can use a checkbox to select the desired element and then utilize its ID for the delete function. Here is an example: let postOffices = [ {postOfficeID: 15, postCode: '3006&ap ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

Attempting to grasp the concept of implementing FormArray

When I execute the following code: this.formArray = new FormArray([ new FormControl(''), new FormControl(''), ]); formControlA() { return this.formArray.at(0); } formControlB() { return this.formArray.at(1); } and then use it ...

What is the best way to eliminate duplicate data from an HTTP response before presenting it on the client side?

Seeking assistance on how to filter out duplicate data. Currently receiving the following response: {username:'patrick',userid:'3636363',position:'employee'} {username:'patrick',userid:'3636363',position:&a ...

How can I prevent the installation of my Ionic 2 application on devices that have been rooted or jailbroken?

I am currently working on a project involving an Ionic 2 and Angular 2 application. I need to implement a feature that checks whether the device is rooted (in the case of Android) or jailbroken (in the case of iOS). I have experimented with various packag ...

Could one retrieve the value of a type and save it as a constant?

Can I achieve something similar to this: type YesType = true; const myVar = GetTypeValue<YesType>(); // In this instance, the value true is assigned Is it feasible to assign other fixed values to constant variables like in C++? ...

Creating a function that is accessible to the entire module

Creating a universal function in a file that is not a module: example.ts: function example() {} You can easily call this function from another file, say test.ts, without needing to import the function from example.ts: test.ts: example(); // calling univ ...