Revise the classification of an instance variable within a subclass

I am pondering about the topic of inheritance and types for instance variables in typescript.

Consider a basic class as shown below:

class Person {
  instanceVariable: Object;
  age: Number;

  constructor(instanceVariable: Object, age: Number) {
    this.instanceVariable = instanceVariable;
    this.age = age;
  } 
};

let alice = new Person({}, 50);  //This will succeed
let sarah = new Person({}, "fifty"); //Typescript will raise an error..

Typescript behaves as expected by throwing an error when attempting to create sarah :). Now, let's contemplate a scenario where another class extends this one, and we need to ensure this class still contains the instance variable but overrides the type.

//Define a simple class that extends and modifies the type
class Student extends Person {
  instanceVariable: String 
}

let bvk = new Student("test", 50);  //This should work
let katie = new Student(50, 50);  //This should not work

Regrettably, this approach does not function as expected. Typescript issues a warning: "Property 'instanceVariable' has no initializer and is not definitely assigned in the constructor."

If we attempt to add a constructor, I am uncertain about how to make it function, as I essentially want to invoke "super" to set the data. Nevertheless, this also triggers the same error in typescript!

class Student extends Person {
  instanceVariable: String;
  constructor(instanceVariable: String, age: Number){
    super(instanceVariable, age)
  }
}

In any case, I may be approaching this issue incorrectly and am keen to discover the most effective way to address it.

Answer №1

To create a more dynamic Person class, consider using a generic type:

class Person<T = object> {
  instanceVariable: T;

  constructor(instanceVariable: T, age: number) {
    // ...
  } 
}

Then, you can extend the Person class with the Student class like this:

class Student extends Person<string> {}

For more information, check out the first point in the Do's and Don'ts section of the TypeScript documentation.

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

Required Ionic form field alert

Currently, I am developing a new app using ionic 3 and I am facing an issue with making inputs mandatory in my ionic-alert controller. Despite going through the ionic-component documentation and api documentation, I couldn't find a solution on how to ...

What is the best way to retrieve a value from an array?

Using ASP.net Core, I receive information from my API. In Angular, the data looks like this: 0: {Id: 3, Role_Name: 'ITAdmin'} 1: {Id: 4, Role_Name: 'Admin'} 2: {Id: 5, Role_Name: 'user'} I want to extract values from this arr ...

Transform the IO type to an array of Either in functional programming with the fp-ts

Looking for assistance with implementing this in fp-ts. Can someone provide guidance? const $ = cheerio.load('some text'); const tests = $('table tr').get() .map(row => $(row).find('a')) .map(link => link.attr(&apos ...

Utilize data binding in Typescript to easily link variables between a service and controller for seamless utilization

Is there a way to overcome the issue of value assignment not binding data in this scenario? For example, using this.arrayVal = someService.arrayVal does not work as intended. The objective is to simplify the assignment in both HTML and controller by using ...

Tsc encounters issues when interacting with AWS services

When attempting to compile TypeScript code into JavaScript using tsc, I encountered constant crashes specifically related to AWS code within the node_modules directory. Despite my efforts to resolve the issue by adding skipLibCheck to my tsconfig file, inc ...

Encountering Next.js Hydration Issue when Using Shadcn Dialog Component

While working on a Next.js project, I came across a hydration error when utilizing the Shadcn Dialog component. The specific error message reads: "Hydration failed because the initial UI does not match what was rendered on the server." Highligh ...

Display options based on the value selected in the preceding selection

How can I dynamically display select options in an Angular select based on a previously selected value? Take a look at the code snippet below. Here, I have implemented a conditional display of select options (Target 1/Target 2) based on the value selected ...

Defining variables within a jQuery function

Within my initialization function (init), I have defined some variables and an animation that utilizes those variables. The challenge arises when I want to use the same animation/variables in my clickSlide function. http://jsfiddle.net/lollero/4WfZa/ (Un ...

Enhancing data validation and converting strings to dates with Nest.js - DTO approach

Anticipating the upcoming request to adhere to the ISO 8601 standard timestamp format, something similar to "2023-12-04T15:30:00Z" (typically embedded as a string within JSON data that needs conversion to a JavaScript Date object). This is my Data Transfe ...

What is the best way to clear a token from SessionStorage upon exiting an Angular application?

I need to clear my sessionStorage every time I exit my application. App Module: export class AppModule implements OnInit, OnDestroy{ constructor(private overlayService: OverlayService, private logger: LoggerService, private userService: UserService, pr ...

Issue encountered while executing jest tests - unable to read runtime.json file

I've written multiple unit tests, and they all seem to pass except for one specific spec file that is causing the following error: Test suite failed to run The configuration file /Users/dfaizulaev/Documents/projectname/config/runtime.json cannot be r ...

Count the occurrences of a specific value type in SQL

Basically, I have a sequence of numbers in one line and need to count how many times each number appears. For instance: 3 2 9 4 3 3 4 3 4 3 3 4 4 3 3 3 3 3 3 3 3 3 3 3 3 3 2 3 3 3 3 3 3 4 3 3 4 13 13 4 3 3 13 3 13 13 13 13 13 13 13 13 13 9 4 4 4 4 3 5 3 9 ...

Discover a more efficient method for expanding multiple interfaces

Hey there, I'm having some trouble with TypeScript and generics. Is there a better way to structure the following code for optimal cleanliness and efficiency? export interface Fruit { colour: string; age: number; edible: boolean; } export inte ...

I'm having trouble with DefaultBindingProperty, I need to retrieve the bound value from the class property

For my project, I am in the process of creating some entities (class) and would like to establish a default binding property for them. Here is an example: namespace MyNamespace { [System.ComponentModel.DefaultBindingProperty("Name")] public class ...

A guide on instantly updating displayed flat/section list elements in React Native

I am in the process of creating a screen called ContactListScreen. The direct child of ContactListScreen is ContactItems, which is a sectionList responsible for rendering each individual ContactItem. However, I have encountered a problem where my ContactIt ...

How to Retrieve Observable<Record<string, boolean>> Value with the Help of AsyncPipe

My service retrieves permissions for the currently logged-in user as a record. The necessary observable is declared in my TypeScript file as a member variable: permissionsRecord$: Observable<Record<string, boolean>>; When I call the service, ...

Error message in Angular: Unable to locate a differ that supports the object '[object Object]' of type 'object.' NgFor is only able to bind to iterables like Arrays

When making an API call in my Angular project, I receive the following JSON response: { "data": { "success": true, "historical": true, "date": "2022-01-01", "base": "MXN&quo ...

Converting Objects to Arrays with Angular Observables

After searching extensively on SO for answers regarding item conversions in Javascript/Angular, I couldn't find a solution that addresses my specific problem. When retrieving data from Firestore as an object with potential duplicates, I need to perfor ...

Next.js focuses solely on rendering markup and does not run any custom code

I am in the process of creating a website, where currently the only functionality available is to change themes by selecting an option from a dropdown menu (the theme is an attribute that uses CSS variables). Everything was functioning properly, however t ...

Asynchronous execution of Angular 2 services

Currently, I am working on a project that utilizes Angular and RxJS. My approach involves creating an injectable class responsible for fetching data from a JSON source as shown below: import {Injectable, Inject} from '@angular/core'; import {Ht ...