Could it be a glitch or the intended functionality when a Typescript derived class static property returns undefined?

Currently, I am delving into typescript and have stumbled upon a peculiar behavior. It seems there are multiple instances of a static property in this scenario; one for the person class and another for the student class. To my surprise, while exploring similar situations in other languages like C#, I discovered that there is only one instance shared by the declaring class and all classes derived from it.

class person
{
    name : string 
    static maxAge : number
    constructor(name:string)
    {
        this.name = name
    }
}
class student extends person
{
    standard : string
    constructor(name:string,standard : string)
    {
        super(name);
        this.standard = standard;
    }
}
person.maxAge = 120;
console.log(person.maxAge);
console.log(student.maxAge);

Here are some burning questions on my mind:

  1. I'm curious as to why the static property is not shared with the derived class.
  2. Could it be possible that the compiler is overlooking something crucial here, thereby failing to flag any compilation errors?

Answer №1

I want to know why static properties are not shared with derived classes?

They are shared at the moment of inheritance. Instead of setting person.maxAge = 120;, you should do it this way:

class person
{
    name : string 
    static maxAge : number = 120
    constructor(name:string)
    {
        this.name = name
    }
}
class student extends person
{
    standard : string
    constructor(name:string,standard : string)
    {
        super(name);
        this.standard = standard;
    }
}
console.log(person.maxAge);
console.log(student.maxAge);

Is the compiler missing something here that prevents giving a compilation error?

No, the compiler trusts you just like in this example:

let foo: number;
console.log(foo); // No error
foo = 123;

The compiler isn't psychic (although TypeScript can feel like that sometimes 🌹) but it does its best to prevent errors.

Answer №2

  1. JavaScript follows a prototype-based structure, so the property is shared through the prototype chain. This means when searching for student.maxAge, the runtime will look in the current object, then its prototype, and continue up the chain of inheritance until it finds maxAge in the prototype of person.

https://i.sstatic.net/SSqfQ.png

  1. Your code snippet contains no TypeScript or JavaScript errors.

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

Encountering the "Vue is not a function" issue while using my to-do list application

I've created a to-do app where clicking on an item should mark it as completed. However, I encounter an error when trying to toggle the completion status of an item imported from Firebase: Error in v-on handler: "TypeError: todo.toggleChecked ...

Angular 6 allows for the use of radio buttons to dynamically enable or disable corresponding fields

Here is the HTML code for a row containing radio button selections: <div class="form-row"> <div class="col-md-3 mb-3"> <div class = "form-group form-inline col-md-12 mb-3"> <div class="form-check form-check-inl ...

Having trouble configuring custom SCSS Vuetify variables with Vue 3, Vite, Typescript, and Vuetify 3

Having some trouble with custom variables.scss in Vuetify. Looking to make changes to current settings and added my code on stackblitz. Check it out here Been going through Vuetify documentation but can't seem to pinpoint the issue. Any assistance w ...

Jest unit tests in Angular using Typescript are not detecting failures when it comes to console errors or unrecognized elements

In my Angular Typescript project, I am facing an issue with my Jest unit test. The test does not fail even if a component (e.g., mat-paginator without importing MatPaginatorModule in configureTestingModule) or template bindings (e.g., [mask] directive from ...

Tips for waiting for an Http response in TypeScript with Angular 5

Is it possible to create a function that can retrieve a token from a server, considering that the http.post() method generates a response after the function has already returned the token? How can I ensure that my function waits for the http.post() call t ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Creating nested Angular form groups is essential for organizing form fields in a hierarchical structure that reflects

Imagine having the following structure for a formGroup: userGroup = { name, surname, address: { firstLine, secondLine } } This leads to creating HTML code similar to this: <form [formGroup]="userGroup"> <input formCon ...

What is the most effective method for integrating templates using AngularJS and Webpack2?

UPDATE: I haven't come across a method to import templates using an import statement rather than require, but I have realized that I can streamline my configuration. In the webpack config, opt for html-loader over ngtemplate-loader for /\.html$/ ...

Using RxJS to merge various HTTP requests into a unified and flattened observable array

Struggling with combining multiple http get requests simultaneously and returning them as a unified, observable array. In my current setup, the method returnNewCars() retrieves Observable<ICar[]> by executing a single http get request. However, in t ...

Troubles with Declaration Merging in Angular 2 Implementation

I'm currently working on incorporating a custom RxJS operator into my project, following the steps outlined in this particular answer. Below are the relevant code snippets from my application: rxjs-extensions.ts import { Observable } from 'rxjs ...

Every variable declaration that follows must match the data type of the initial declaration

Here's the link I'm using to kickstart a sample node js project with webworker-thread: https://www.npmjs.com/package/webworker-threads Below is my TypeScript code snippet: var Worker = require('webworker-threads').Worker; var worker ...

You were supposed to provide 2 arguments, but you only gave 1.ts(2554)

Hey everyone, I hope you're having a good morning. Apologies for the inconvenience, I've been practicing to improve my skills and encountered an issue while working on a login feature. I'm trying to connect it to an API but facing a strange ...

Is there an Angular @input attribute that concludes with an exclamation mark?

This source code showcases the usage of @Input properties with an exclamation mark (!) at the end. An example is shown below: @Input() token!: StripeToken The presence of ! in this case signifies a non-null assertion operator, but what is the significanc ...

Typescript having issues compiling to commonjs/es2015 accurately

I currently have Node v14.5.0 installed and I'm using ts-node-dev in my development environment However, I am encountering an error every time I try to compile to JS. Initially, I attempted with the following tsconfig: "target": "es5& ...

Unable to initiate ng-click event in AngularJS

Looking to trigger a function in TypeScript from the view using AngularJS. My technology stack includes AngularJS, TypeScript, and ASP.Net MVC3. Here is the link in the UI: <div id="left_aside" ng-controller="MyGivingPortfolioController"> <div ...

Tips on incorporating jstree into an Angular 2 application with TypeScript and @types/jstree

Hello, I am new to ng2 and have a question that may seem obvious to some. I recently installed the jstree library using npm in my angular-cli application by running the command npm i jstree --save. Following this, I also installed the types for jstree wi ...

The SDK directory for TypeScript 1.3 in Visual Studio 2013 does not include the necessary tsc.exe file

Exciting news! Typescript v1.3 has been officially announced today. To fully utilize this update, I quickly installed the power tools update for VS2013. Upon completion of the installation, my Visual Studio environment now recognizes the "protected" keywo ...

Standardized identification code

My request response needs to be defined, but the key name may vary. It will always be a string, but the specific key depends on the request. These are the possible responses: { someRequest: { message: 'success', status: 200 } } { someOtherReques ...

The function navigator.canShare() encountered a permissions denial while running in Typescript

Currently, I am in the process of developing an Angular8 PWA and have successfully implemented webshare to share text content. To my excitement, Chrome has now extended its support for file sharing starting from May 2019. However, while attempting to int ...

This TypeScript error occurs when the type of a CSS file lacks an index signature, resulting in an implicit 'any' type for the element

Currently in the process of transitioning a React app to utilize Typescript. Encountering an error message that reads: ERROR in [at-loader] ./src/components/Services/Services.tsx:34:29 TS7017: Element implicitly has an 'any' type because typ ...