Can Typescript classes be hoisted if I use two classes in my code?

Exploring Class Definitions

Certain Rules to Comply With

Ensuring that the class is defined in advance helps avoid errors.

class Polygon {
  log() { console.log('i am polygon'); }
}
const p = new Polygon();  // Expected: no errors
p.log();

Understanding Hoisting of Classes

Knowing that classes are not hoisted explains this error outcome.

const b = new Bolygon();  // Expected: Uncaught TypeError
b.log();
class Bolygon {
  log() { console.log('i am bolygon'); }
}

Questioning Class Hoisting

In situations like this code(playground link), will the class be hoisted?

The confusion arises when new Hero() does not trigger an error as seen below. Is class Hero being hoisted?

class AppComponent {
  hero = new Hero('foo') // Why is there no error?
}
class Hero {
  constructor(public name: string){}
}

Answer №1

The explanation lies in the sequence of evaluation within your code:

hero = new Hero('foo')

This line is executed only after AppComponent is instantiated, by which point the Hero class has already been evaluated. On the other hand, in the second snippet:

const b = new Bolygon();

This line is evaluated before the actual class definition of Bolygon.

If you attempt to make AppComponent.hero static, you will encounter an error:

class AppComponent {
  static hero = new Hero('foo') // error: Hero is not a 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 best practices for managing item spacing in React or React Native

I am facing some challenges while trying to adjust the spacing of my components. My goal is to have the grid occupy 90% of the screen, with the gear icon taking up the remaining 10% <View style={{ paddingLeft: insets.left, padding ...

Encountered an issue while attempting to integrate Nebular into my Angular application

As a newcomer to Angular, I decided to try installing Nebular using the command ng add @nebular/theme. However, I encountered an error in the process. Upon entering the command into my terminal, the following error message appeared: ? Which Nebular theme ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...

top margin is functioning properly in Internet Explorer, but not in Google Chrome

margin-top is behaving differently in IE compared to Google Chrome. Two menus are supposed to be displayed one above the other in my design. The issue lies in the line margin-top:30%; within .anothermenu ul. In Chrome, the second menu appears above the f ...

Unable to call Ionic component function using ref in Vue3

I'm attempting to utilize the closeSlidingItems method of the IonList element in order to automatically close the sliding item after clicking a button that appears from behind once the item is slid to the right. My approach involved referencing IonLi ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

Simple JavaScript validation for inputting names

Hey there, I'm a beginner in javascript and I am struggling with a simple input validation using else if statements. Every time I run the code, it goes directly to the else condition. Can someone please assist me? <!DOCTYPE html> <html lang=& ...

Linking asynchronous AJAX requests using Angularjs

Currently in my AngularJS project, I have created a service with multiple functions that return promises. The AJAX Service I've Created: angular.module('yoApp') .factory('serviceAjax', function serviceAjax($http) { return ...

Avoid triggering child states in ui-router

Here is the progress I have made with ui-router states: $stateProvider .state('tools', { url: '/tools/:tool', template: '<div ui-view=""></div>', abstract: true, onEnter: function ($stateParams, ...

Encountering a 500 internal server error or receiving an error message stating "invalid value for stripe.confirmCardPayment

I'm currently working on implementing a payment component for my React app using Stripe for the first time. Despite following a tutorial closely, I keep encountering an internal server error or receiving an "invalid value for stripe.confirmCardPayment ...

Utilize client-side script in nodejs to share module functionalities

I created a function within the user controller module to verify if a user is logged in on the site: exports.isLoggedIn = function(req, res, next) { if (req.user) { return true; } else { return false; } }; I'm unsure of h ...

Retrieve the identifier of the higher-order block when it is clicked

When I have a parent block with a nested child block inside of it, I expect to retrieve the id of the parent when clicked. However, the event target seems to be the child element instead. Is there a way for JavaScript to recognize the parent as the event ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

Discovering the Javascript Code Executing on a <span> element with the Help of Chrome Inspector or Firebug

I have encountered a situation where a website is dynamically generating information into <span></span> tags using jQuery. The span has a class of "Price" and an id corresponding to a Product Code, with the data being pulled from a JSON data sh ...

Steps to access arrays that are embedded in a file and are loaded asynchronously

https://gyazo.com/e80eea9f69c0cbb52cc7929d0a46ea2f The name of the object is totalCount. How can I retrieve the count from it? Object.result was my first attempt, but it returned undefined. For my second attempt: var count = totalCount.resu ...

Retrieving the value from a concealed checkbox

I have been searching everywhere, but I can't seem to find a solution to this particular issue. There is a hidden checkbox in my field that serves as an identifier for the type of item added dynamically. Here's how I've set it up: <inpu ...

Configuration of an MVC-based web application

As a newcomer to web application development, I am currently working on building a web application using the Model-View-Controller pattern. My setup includes a MySQL database for the Model, JSP pages for the Views, and a DAO for the Controller. I am looki ...

Dynamically inserting templates into directives

I've been attempting to dynamically add a template within my Angular directive. Following the guidance in this answer, I utilized the link function to compile the variable into an HTML element. However, despite my efforts, I haven't been success ...

The next-routes server.js encounters an issue: TypeError - the getRequestHandler function is not defined within the routes

I encountered an issue in my server.js file. Here is the code snippet causing the problem: const { createServer } = require('http'); const next = require('next'); const routes = require('./routes'); const app = next ({ dev: ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...