Using super() conditionally in Typescript

Is it possible to conditionally load the super class based on a parameter in TypeScript? I am facing an issue where I need to send a parameter in super() based on a specific condition, but placing an if statement before super() results in a compilation error. Is there a workaround for this?

Below is the code snippet that I have tried, but it's not working as expected. I need to pass or block the dependencies parameter (ENGINE_MODEL) in super() depending on a certain condition.

Any suggestions on how to achieve this functionality?

export class CreateChrStructureNodeControlComponent extends StructureNodeControl {
    constructor(private changeRequestCreateService: CreateChangeRequestService) {
    if(some condition = 'SF')
        super(changeRequestCreateService,
            PLANT,
            ENGINE_MODEL);
    else 
         super(changeRequestCreateService,
            PLANT)
      ;
    }
}

Superclass :

export class StructureNodeControl extends BaseTypeaheadControl<TypeahaedLookupTableItem> {
    constructor(changeRequestCreateService: CreateChangeRequestService, ...dependencies: string[]) {
        super(STRUCTURE_NODE,
            changeRequestCreateService.getStructureNodes,
            TypeahaedLookupTableItem,
            ...dependencies);
    }

Answer №1

To customize the dependencies for your superclass, simply modify the parameter type from a varargs string array to a standard string array. This allows you to selectively include or exclude dependencies based on certain conditions.

For example, adjust the superclass as follows:

export class StructureNodeControl extends BaseTypeaheadControl<TypeahaedLookupTableItem> {
    constructor(changeRequestCreateService: CreateChangeRequestService, dependencies: string[]) {
        super(STRUCTURE_NODE,
            changeRequestCreateService.getStructureNodes,
            TypeahaedLookupTableItem,
            ...dependencies);
    }

Then, in your subclass:

export class CreateChrStructureNodeControlComponent extends StructureNodeControl {
    constructor(private changeRequestCreateService: CreateChangeRequestService) {
       super(changeRequestCreateService,
             [
              PLANT,
              some_logic === 'SF' ? ENGINE_MODEL : null
             ].filter(Boolean)
       ); // Remove any null values
    }

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

Using jQuery, is it possible to retrieve the product name and image dynamically?

I'm currently working on implementing an add to cart functionality using jQuery. When the add to cart button is clicked, the product name and image should be displayed. I can achieve this statically but I need help figuring out how to dynamically retr ...

Cannot trigger event ascn.onchange does not exist as a function

Need to trigger the onChange function and pass parameters within it. Here's what I have tried: setTimeout(function() { document.getElementById(input.key)?.onchange({}) }, 200); Encountering the following error message: cn.onchange is not a function ...

How can I iterate through a variable in TypeScript?

initialize() { var elements = []; for (let i = 1; i <= 4; i++) { let node = { name: `Node ${i}` }; elements.push({ [`node${i}`]: node }); if (i < 4) { let edge = { source: `node${i}`, target: ...

Implementing a "Click to view additional comments" feature using PHP and AJAX

I've been working on setting up a video commenting system, but I'm stuck on getting my "load more" button to function properly. Despite checking my PHP script and finding no errors, nothing seems to be happening when I click the button. As someon ...

Finding specific data with MongoDB's query syntax

I am working with a mongoDB "users" collection in JSON format. My objective is to retrieve all the data where privacy is set to true. How can I accomplish this? { "name" : "Maria Kari", "social" : [ { "facebook" : "www.fb.com/ ...

How can you extract information from a text document and seamlessly incorporate it into an HTML webpage?

I am currently working with an HTML file structured like this.. <html> <body> <table border="1" cellpadding="5"> <tr> <td>Some Fixed text here</td> <td id="data">---here data as per values in external text file--- ...

Using ng-if to compare dates in AngularJS without considering the year

I am facing a comparison issue with dates in my code. I have one date that is hardcoded as the first day of the month, and another date coming from the database (stored in a JSON object). When I compare these dates using ng-if, it seems to ignore the year ...

What method does jqGrid use to dynamically update the selection options list based on the status data?

Currently, I am utilizing jQgrid for displaying a list with data retrieved through Ajax. The list is displaying properly without any issues. However, my challenge lies in dynamically populating the list of options based on the status value received. Area ...

Show information retrieved from one API request within another API request

Currently, I am in the process of retrieving data from the Youtube API by utilizing 2 separate requests. One request is used to fetch a list of videos, while the other request provides details for each individual video. The initial request successfully di ...

Can wildcard paths be imported in React using Typescript?

Is there a way to dynamically import a React Typescript Component from a wildcard path, similar to the following code snippet? const Component = loadable( () => import(`../../../src/**/*/${component_name}`), ); I have searched numerous solutions on ...

Problem with JavaScript and Basic HTML5 Canvas

I'm trying to dive into learning about using a canvas, but I just can't seem to get this basic code to work. Does anyone know what I might be doing wrong? Link to jsfiddle <canvas id="ctx" width="500" height="500" style="border:1px solid #00 ...

angular 6 personalized material icons with ligature assistance

Can I create my own custom material icons with ligature support? Currently, I use svgIcon to get Custom Icons, Is there a way to make custom icons that support ligatures? Here is my current code snippet: app.component.ts import { Component } from &ap ...

Bootstrap Tags Input - the tagsinput does not clear values when removed

I am attempting to manually remove the input value from bootstrap-tags-input when the x button is clicked, but the values are not changing in either the array or the inputs. This is the code I have tried: $('input').tagsinput({ allowDuplica ...

What are the steps to save data on a user's computer through a web browser?

Is it feasible to save data in the client's computer using a web browser and jQuery code to interact with the file system? ...

Utilizing AngularJS element.find results in modifications to my objects

Encountering an issue with angularJS when trying to locate elements. It appears that the objects are being altered when using element.find('type').attr('id' ,someid); Here are some additional details: The directive is only used in on ...

`Finding it difficult to halt the spread of events in reactJs`

One of my conditions involves a simple dropdown menu: handleDropdown = (e) => { if (e.type === "focus") { console.log("inside dropdown focus"); this.setState({ dropDownDis: "block" }) } else if (e.type === "blur") { console.lo ...

Sort the currency column in an HTML table through JavaScript

I have a code snippet below that I'm currently utilizing to arrange columns in an HTML table. The code works perfectly for alphabetical sorting and also for single-digit numbers. However, when attempting to sort a column containing currency values, t ...

The functionality of this javascript setTimeout is quite peculiar when it comes to working with ajax requests

I have created this script to monitor the progress of an import script. The script is designed to execute a function that makes an http request every X seconds. function checkImportProgress() { //if(import_status != 'finalizat') { alert("Che ...

Is there a way to dynamically load a file on scroll using JavaScript specifically on the element <ngx-monaco-diff-editor>?

I've been attempting this task for over a week now in Angular without success. Would someone be able to provide guidance? The onContainerScroll() function isn't being triggered, and I'm considering using JavaScript instead. How can I achiev ...

Incorporating promises with ajax to enhance functionality in change events

Consider the scenario where you trigger an ajax request upon a change event in the following manner: MyClass.prototype.bindChangeEvent = function(){ $(document).on('change', '#elementid', function(){ var $element = $(this); $ ...