Embracing Typescript version 2.7 and above allows for utilizing multiple types within a parameter, enabling developers to efficiently handle specific properties

Imagine a scenario where a ChildClass is extending the ParentClass. You can view the code on Stackblitz here.

The ChildClass simply adds a public property called "brainPower":

class ParentClass{

  _me: string;

  constructor() {
    this._me = "I'm a parent";
  }

  whoAmI(): string {
    return this._me;
  }
}

class ChildClass extends ParentClass {

  public readonly brainPower = 42;

  constructor() {
    super();
    this._me = "I'm a child";
  }
}

In the code, there is a method named "doStuff" that takes a parameter which could be of either type:

class Program {

  static main() {
    Program.doStuff(new ParentClass());
    Program.doStuff(new ChildClass());
  }

  static doStuff(anInstance: ParentClass | ChildClass){

    console.log('[Program] > Processing > ', anInstance.whoAmI());

    if(anInstance.brainPower){
      console.log('[Processing] > ', anInstance.whoAmI(), ' > I can brain as much as ', anInstance.brainPower);
    }
  }
}

The issue arises when the Typescript compiler shows the error message:

Property 'brainPower' does not exist on type 'ParentClass | ChildClass'.

So the real Question here is how to define multiple possible types for a parameter and make sure that TypeScript can correctly understand it, allowing properties specific to one type only to be accepted?

Answer №1

To allow for flexibility, you can specify that the function parameter accepts any instance of the ParentClass.

Rather than verifying the existence of a property, consider checking if the provided object is an instance of the ChildClass.

if (anInstance instanceof ChildClass) ...

When this condition is met, the TypeScript compiler will recognize the object as an instance of ChildClass within the scope of the if statement.

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

Step-by-step guide on crafting a harmonious row of a label and a responsive button group

One of my projects involves a form that contains a list of elements. I want this form to be responsive and suitable for all screen sizes. When I initially run the project on a larger screen, everything looks good. However, when I resize the screen to a sma ...

Issue: Encountering an ObjectUnsubscribedError while using Observables in RxJS and Angular2

Currently, I am in the process of self-teaching Angular2 and realize that I need to find better resources. One issue I am facing is related to moving my data calls to a service and utilizing Reactive Subject & BehaviorSubject as recommended by a friend. Wh ...

Save the chosen information into the database

My goal is to insert a Foreign key, acc_id, into the patient_info table from the account_info table. I have successfully retrieved the data from my database and now I want to use it as a Foreign key in another table. Here is the code snippet: try { $ ...

What steps can be taken to fix error TS2731 within this code snippet?

I've been working through a book and encountered an issue with the code below. // This code defines a function called printProperty that has two generic type parameters function printProperty<T, K extends keyof T> (object: T, key: K) { let pro ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

The dynamic form functionality is experiencing issues when incorporating ng-container and ng-template

I'm currently working on a dynamic form that fetches form fields from an API. I've attempted to use ng-container & ng-template to reuse the formgroup multiple times, but it's not functioning as anticipated. Interestingly, when I revert b ...

Switch the ngClass on the appropriate ancestor element for the dropdown menu

Utilizing Angular CLI version 8.3.0, I aim to construct a sidebar featuring a drop-down menu. My objective is to apply the "open" class to toggle the opening of the drop-down section. However, the current challenge I am encountering is that when I click to ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

Tips for troubleshooting the error "Cannot locate module mp3 file or its associated type declarations"

Seeking guidance on resolving the issue with finding module './audio/audio1.mp3' or its type declarations. I have already attempted using require('./audio/audio1.mp3'), but continue to encounter an error. ...

The type string[] cannot be assigned to type 'IntrinsicAttributes & string[]'

I'm attempting to pass the prop of todos just like in this codesandbox, but encountering an error: Type '{ todos: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'. Property 'todos' does not ex ...

Locate and refine the pipeline for converting all elements of an array into JSON format using Angular 2

I am currently working on implementing a search functionality using a custom pipe in Angular. The goal is to be able to search through all strings or columns in a received JSON or array of objects and update the table accordingly. Here is the code snippet ...

Why is there a false positive in the onChange event for the number type in React TypeScript?

I encountered an error on line 24 Argument of type 'string' is not assignable to parameter of type 'SetStateAction'.ts(2345) This issue occurred while working with TypeScript for a React experiment. const App: React.FC = () => ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...

What is the best way to modify an existing object in an Observable Array in Angular?

As I work on my Ionic 5 / Angular application, a challenge arises when attempting to update a Conversation object within the existing array of Conversation: private _conversations = new BehaviorSubject<Conversation[]>([ new Conversation( & ...

Utilizing Variables in TypeScript to Enhance String Literal Types

Here are my codes: export const LOAD_USERS = 'LOAD_USERS'; export const CREATE_USER = 'CREATE_USER'; export interface ACTION { type: string, payload: any } I am trying to limit the possible values for ACTION.type to either 'L ...

What causes an array to accumulate duplicate objects when they are added in a loop?

I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request. let response: TEventResponse ...

Can you explain the mechanics behind Angular Component CSS encapsulation?

Is it possible to avoid CSS conflicts when using multiple style sheets? Consider Style 1: .heading { color: green; } And Style 2: .heading { color: blue; } If these two styles are applied in different views and rendered on a layout as a Partial Vi ...

Implementing a string replacement within an array of objects using TypeScript

I have a collection of array objects displayed below [ { "subjectID": 1 "Chosen" : "{subjectsChosen:Python,java,Angular}" "password": "{studentpw:123456abcd}" }, { "subjectID": 2 ...

What is the best way to enhance the object type within a function parameter using TypeScript?

If I have a specified type like this: type Template = { a: string; b: string; c: string } I want to utilize it within a function, but with an additional parameter. How can I achieve this efficiently? When attempting to extend the type, TypeSc ...

JavaScript file encountering a Typescript issue with a property defined in a subclass

Currently, I am utilizing Typescript to validate my Javascript files. One issue I have encountered is that when I inherit from a class, Typescript does not recognize the types of the properties in the parent class. I am unsure if I am overlooking something ...