What is preventing me from dynamically generating a property?

As someone who is new to TypeScript, I have a question regarding defining properties. In JavaScript, we can define a property dynamically like this:

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

However, in TypeScript, it doesn't work the same way:

class Rectangle {
  constructor(height:number, width:number) {
    this.height = height;   //error 
    this.width = width;     //error 
  }
}

I understand that adding an access identifier such as public before the parameters in the constructor like this:

 ...
 constructor(public height:number, public width:number) {...}  //which creates declaration automatically

will solve the issue. But my question is, since TypeScript is supposed to be a superset of JavaScript, shouldn't it support all valid JavaScript syntax as well?

Answer №1

One interesting aspect of TypeScript is that it serves as a strict syntactical superset of JavaScript, incorporating optional static typing within the language.

Additionally, it's worth mentioning that certain features that are not strongly-typed or have similarities to this concept will not function properly in TypeScript due to its nature.

Answer №2

Here is the sequence of steps involved in interpreting a TypeScript (TS) code:

  1. All properties and methods are initialized.
  2. During instantiation, the constructor is called, and the properties mentioned above are assigned default values.

In your provided code snippet:

class Rectangle {
  constructor(height:number, width:number) {
    this.height = height;   //error 
    this.width = width;     //error 
  }
}

The error occurs because there are no properties explicitly defined in the class.

Answer №3

Achieving your goal is possible, but be prepared to go against the language's type-checking feature.

class Rectangle {
  constructor(height:number, width:number) {
    (this as any).height = height;
    (this as any).width = width;
  }
}

const rt = new Rectangle(100, 200);
console.log((rt as any).width);

By casting to any, you gain the ability to perform tasks just like in regular JavaScript.

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

Phaser3 encountering issues while loading files from Multiatlas

Attempting to utilize the multiatlas functionality in Phaser alongside TexturePacker. Encountering this issue: VM32201:1 GET http://localhost:8080/bg-sd.json 404 (Not Found) Texture.js:250 Texture.frame missing: 1/1.png The JSON file can actually be fou ...

How can you create a pop up window that automatically refreshes the original page when closed?

I am currently utilizing the most up-to-date version of jQuery. Upon clicking this button: <input id="ShowImages" class="" type="button" value="images"> The following function is triggered: $("#ShowImages").click(function() { $("#MusicianImag ...

Transforming a massive JSON object into a Blob concerns directly converting it into an ArrayBuffer or Blob to prevent exceeding the maximum string length error

Situation: Within my application, I am encountering the following code: let blob = new Blob([JSON.stringify(json)], {type: "application/json"}); This code sometimes fails because the maximum string length allowed in Chrome is approximately 500M ...

The presence of double quotes in stringified JSON is undesired

I am currently working on a weather forecasting website where the API returns pure JSON data. However, when I convert this data to a string and add it to an element in order to display it on the webpage, I encounter a problem with double quotes appearing. ...

Apply a border to the input field when the user enters or leaves the field, only if the value is

I am managing a few input fields and storing their information in an object. My goal is to click on an input field to focus on it, and if the field is empty or has a length greater than or equal to 0, I want it to display a red border. If I type somethin ...

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicked on?

Is there a way to clear the search box in a wenzhixin bootstrap table without refreshing the page when clicking anywhere on the page? <table id="view_table" data-toggle="table" data-search="true" data-page-list="[5, 10, 20]" data- ...

Error: The `queries` property is undefined and cannot be read (react.js)

Here is the code snippet I am currently working with: import { useState } from 'react' import { QueryClientProvider, QueryClient } from 'react-query' import { ReactQueryDevtools } from 'react-query-devtools' import Navba ...

Locate the Highest Number within a Multi-Dimensional Array and Store it in a Fresh Array

I'm currently tackling a coding challenge that involves working with nested arrays. The task is to find the largest number in each sub-array and then create a new array containing only the largest numbers from each one. Initially, my approach was to d ...

Is there a way to recycle an image and ensure that the web browser only needs to download it once?

Is there a way to effectively reuse the same image multiple times on my website without inefficiently downloading it each time? ...

Creating a button that emerges from another button

Currently utilizing Angular 5, I am looking to add an additional button that will display upon clicking another button. I am considering using the ngIf directive, but I am uncertain about how to target the specific button that was clicked. Here is an exc ...

What is the best way to prevent ngFor from repeating the input values being typed?

How can I prevent the same word from being repeated in all the inputs when using ngFor to create multiple inputs? https://i.sstatic.net/kqh5X.png Here is my code snippet: <div class="" *ngFor="let publication of publications"&g ...

When the NODE_ENV is set to 'production', the global error handler middleware fails to log errors

To ensure proper code format, errors are logged and returned to the client using Postman in development mode, but are not sent back to the client in production mode. The following code represents the global error handler: module.exports = (err, req, res, n ...

Unprocessed Promise Rejection Alert: The function res.status is not recognized as a valid function (NEXT JS)

When I console.log(response), I see the result in the terminal. However, when I use res.status(200).json(response), I encounter an error in my Next.js project: Not Found in the browser. router.get("/api/backendData", async (req, res) => { dbConne ...

tips for sending the database value to the next page with ajax

Struggling to send the database value retrieved through ajax to the next page. Tried several methods but none seem to work. Could anyone provide guidance on how to achieve this? php Successfully connected to the database $sql = "SELECT * FROM `billin ...

Exploring the use of index signatures in TypeScript when working with React

I'm struggling to properly implement the index signature in this code. I have an enum and I need to loop through it to display some JSX on the screen. I understand the error message, but I'm having trouble resolving it in my code. The issue seems ...

Utilizing Ajax for dynamically updating a dropdown menu powered by Javascript

I have a question about implementing ajax in my category drop down box. Currently, I have a JavaScript function that redirects the page when a user selects a category. However, I would like to enhance this by loading the category items dynamically without ...

What factors could potentially cause Internet Explorer to fail in processing conditional comments effectively?

I am currently developing JSP pages with Tomcat and I need to ensure compatibility with IE 7, as requested by the client, along with Firefox and Chrome. Despite including both sets of code in my program, it seems to work perfectly fine for browsers other ...

Connect to Node-Red websocket server

My server is running node-red with embedded functionality. I am attempting to set up a new websocket listener on the server, but when I run the code provided, the websockets in my node-red application stop functioning properly. const WebSocket = require(& ...

How do I implement branch code using TypeScript types in Svelte?

Looking for a solution similar to the one mentioned in Typescript: How to branch based on type, but tailored for Svelte. Despite implementing run-time type guards as suggested, Svelte continues to throw errors. I am dealing with an array called collectabl ...

The functionality of wp_script_is in WordPress seems to be malfunctioning when it comes to

I need to load a certain file only after a specific script has finished loading. Wordpress offers a useful method called 'wp_script_is' for detecting if a script has loaded or not. When I use the jquery handle with "done", it functions as expecte ...