Typescript subtraction operation may result in Undefined

I am a beginner in the world of TypeScript and I'm currently struggling with running this code snippet:

class TestClass
{
  public t: number = 10;

  constructor() {
    this.t = this.t - 1;
    console.log(this.t);
  }
}

var obj = new TestClass();

For those interested, you can find a working example on the TypeScript playground.

After transpiling the code to JavaScript, Chrome's developer console prints 'Undefined' instead of expected '9'.

If anyone could shed some light on why this is happening in both TypeScript and JavaScript realms, I would greatly appreciate it.

Answer №1

When you define the console.log section within a public method, make sure to execute obj.TestClass().

playground

Perhaps consider utilizing a constructor instead?

Answer №2

It appears that the method of the class was not called:

obj.TestClass(); // <---should be called.

See Demo on JSBIN


Unlike Java, Typescript requires using the keyword constructor instead of having a constructor with the same name as the class. In Typescript/Javascript, all other functions are considered as class members.

View Demo on Jsbin with constructor

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

The XML data is valid, however the responseXML property in the XMLHttpRequest response is null

Click here to access the API URL, which returns XML data. However, the responseXML property in the XMLHttpRequest response is coming back empty. How can I retrieve the XML data from the response? document.body.onload = loadXMLDoc(); function loadXMLDoc ...

Creating a responsive database using an Express application and Socket.IO

As I am developing an application using Express Create App, specifically designed to run on Plesk hosting, I have already configured it following the example provided by the official Plesk Node Express project. Everything is working smoothly so far. The ap ...

What is the proper way to integrate EJS tags within script tags in EJS files?

I am encountering an issue with the code in my index.ejs file from YelpCamp, which is a part of Colt Steele's course. const campgrounds = <%- JSON.stringify(campgrounds) %>; I attempted to fix it by changing the code to: const campgrounds = &ap ...

Incorporate an additional javascript document into a VueJS component

What is the most efficient method to include Javascript files in Vue.js components? ...

In a scenario where multiple fields need to be incremented, one can accomplish this by incrementing one field every time while also increasing the other field only if it exceeds a

When trying to decrement class_number, everything works fine. However, the issue lies with number_of_classes not being decremented due to the usage of the $gt operator. posts.update({ 'title':doc.title, 'author':doc.author, 'class ...

Can you choose an option from a dropdown menu without relying on jQuery?

Can a dropdown list item be selected using AngularJS instead of jQuery? I have successfully accomplished this using jQuery, but I am curious if it can be done with AngularJS. This is how I achieved it using jQuery: var dropdownlist = $("select").data("k ...

What is the best way to run tests on this asynchronous function using Jasmine?

My role in the service is listo: function () { var promiseResolved = $q.defer(); setTimeout(function () { promiseResolved.resolve(true); }, 2000); return promiseResolved.promise; } During my testing ...

What could be causing the onClick event handler to trigger twice in my create-react-app?

Does anyone know why the "upvote" onClick handler is triggering twice? Even though the logs show it's only running once, the score increases by 2 export default class Container extends Component { constructor(props) { super(props); this.sta ...

Avoiding memory leaks in Reactjs when canceling a subscription in an async promise

My React component features an async request that dispatches an action to the Redux store from within the useEffect hook: const fetchData = async () => { setIsLoading(true); try { await dispatch(dataActions.fetchData(use ...

Issue with Guild Member Add functionality in discord.js is not functioning as expected

I'm facing an issue with my code where the bot does not send a welcome message when a user joins, despite having everything set up correctly. Even when a user leaves, there is no farewell message being sent either. Here is the code I am using: bot.on ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

The ng-blur functionality will only trigger if the click event occurs within the bounds of the textbox

I am facing an issue with a textbox that should display a certain value even after being deleted. When the input is cleared and clicked away from, I want the value to reappear in the textbox. Currently, there seems to be a problem with this functionality ...

What is the best way to align the 'Typography' component in the center?

Attempting to center it using flexbox with justify-content did not yield the desired result. I also tried replacing the Typography component with a div tag, but still no success. import {AppBar,Zoom,Toolbar,Typography,CssBaseline,useScrollTrigger,Fab,ma ...

Encountering an "Unexpected token '{'" error while attempting to import chart.js is likely due to the import call expecting only one argument

I'm currently working on a node.js app that utilizes chart.js for visualizations. However, I'm running into errors when trying to import and use Chart. To serve chart.js to the client, I used npm to install it and then added the following code: ...

A guide on creating a clickable polygon in Vue.js using Konva

Is there a way to create an interactive polygon in Vue Konva where I can set each corner with a click? I haven't been able to find any resources other than the v-polygon which only creates predefined polygons. ...

URL Labeler StateProvider: A unique StateProvider that adds a distinctive label to the

I need help figuring out how to add a user-friendly URL at the end of the current URL using $stateProvider. As an example, on StackOverflow's question pages, the URL format is stackoverflow.com/questions/(question_id)/(question title). I want to repl ...

Guide to leveraging tanstack table v8 for sorting data within a specific date range

Received data from API: const abc = [ { date: '2023-12-8', value: 'mop' },{ date: '2023-10-8', value: 'qrs' } ] How can we create a date range using two input fields when the dates are in string forma ...

Assigning information to a button within a cell from a dynamically generated row in a table

I've been diligently searching through numerous code samples but have yet to find a solution to my current dilemma: My HTML table is dynamically generated based on mustache values and follows this structure: <tbody> {{#Resul ...

Looking for a way to trigger a function on JSTree's refresh event

I have searched through many posts here but cannot find what I am looking for. The version of JSTree that I am using is 3.3.3. My goal is to select a node after a create_node event triggers an AJAX request. Subsequently, JSTree fires the rename_node eve ...

Best practice for sending a Facebook token securely between client and server

I'm facing a dilemma on how to securely transfer a user's Facebook token from their client to my server. Currently, I have the following approach in mind: The user accesses a webpage and logs in to Facebook; Facebook token is obtained; User&apo ...