Creating a dynamic number of properties with different names in Typescript can be achieved by using a loop

I have a requirement for enabling type checking on a specific class
Here is the relevant code snippet:

class FlightFilter implements Filter {
  get filters() {
    return {
      departTime: { name: 'Departure Time', type: FilterTypes.Range },
      price: { name: 'Price Range', type: FilterTypes.Range },
      flightType: { name: 'Flight Type', type: FilterTypes.CheckboxList },
      flightClass: { name: 'Flight Class', type: FilterTypes.CheckboxList },
      airline: { name: 'Airline', type: FilterTypes.CheckboxList },
      airports: { name: 'Airports', type: FilterTypes.CheckboxList }
    };
  }

  fillData() {
    for (const filter of this.filters) {
      console.log(filter);
    }
  }

  // Other methods and properties implementations...

}

I attempted to create an interface for it but I am unsure how to handle multiple instances of a property with dynamic names
Similar to this concept:

interface Filter {
    filters(): Object;
    fillData(): void;

    // This is where I want to have multiple instances
    [name: String](ticket: Object): Boolean;
    [name: String]DataGenerator(): void;
    [name: String]Model: any
}

Please note that the above code is extracted from my JavaScript project and I am looking to transition to TypeScript

Answer №1

I am grateful to "BobobUnicorn" from the typescript discord community for providing me with a solution. This is truly outstanding!

type Filter<T extends { filters: unknown }> = {
  filters: T['filters'];
  fillData(): void;
} & {
    [K in keyof T['filters']]: (ticket: unknown) => boolean;
  } & {
    [K in keyof T['filters'] as `${K & string}DataGenerator`]: () => void;
  } & {
    [K in keyof T['filters'] as `${K & string}Model`]: any;
  }

enum FilterTypes {
  Range = 1,
  CheckboxList = 2
}

class FlightFilter implements Filter<FlightFilter> {
  get filters() {
    return {
      departTime: { name: 'زمان رفت', type: FilterTypes.Range },
      price: { name: 'بازه قیمتی', type: FilterTypes.Range },
      flightType: { name: 'نوع پرواز', type: FilterTypes.CheckboxList },
      flightClass: { name: 'کلاس پروازی', type: FilterTypes.CheckboxList },
      airline: { name: 'شرکت هواپیمایی', type: FilterTypes.CheckboxList },
    };
  }

  fillData() {
    // for (const filter of this.filters) {
    //   console.log(filter);
    // }
  }

  departTime(ticket: any) {
    return true;
  }

  departTimeDataGenerator() { }

  departTimeModel = null;

  price(ticket: any) {
    return true;
  }

  priceDataGenerator() { }

  priceModel = null;

  flightType(ticket: any) {
    return true;
  }

  flightTypeDataGenerator() { }

  flightTypeModel = null;

  flightClass(ticket: any) {
    return true;
  }

  flightClassDataGenerator() { }

  flightClassModel = null;

  airline(ticket: any) {
    return true;
  }

  airlineDataGenerator() { }

  airlineModel = null;

}

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

"Displaying an array using React Hooks' useState causes the content to

I want to enhance my image uploading functionality in useState by implementing a specific function. Once the images are uploaded, I need to render them on the page. However, I am facing an issue with rendering the returned array. Here is the current code ...

"Showing Images in a Slider: A Step-by-Step Guide

I'm facing an issue with displaying images in a slider. The problem is that the images are stacking vertically instead of appearing side by side in a slideshow. Below is how I have structured my code: @if (Model.Photos.Count > 0) { <div s ...

The elements in my code are not displaying as expected

This is my jQuery script: $("#options").popup(null, Settings.DialogOptions) .on("onOk", function(){ Settings.SaveSettings( ); Settings.CloseSettings( ); switch(Settings.GetSetting("displayId")){ case "true": $("#nextId").s ...

The functionality of a switch statement relies on the presence of a React-Router

Is there a way to dynamically change the text in a paragraph based on which Route is currently enabled? I tried using a switch statement, but I'm unsure of how to implement it. Any suggestions or ideas? import React from 'react'; import &ap ...

Error encountered when trying to show a modal using a PHP script

I'm encountering an issue with the modal system on my website. Let me share some code snippets: MODALS ARE BUILT WITH W3.CSS LIBRARY modal.js (including debug statements) let modal = null; let title = null; let content = null; $(document).ready(() = ...

How can I globally assign a JavaScript variable based on an AJAX response?

Here is the ajax code I have: <script> $('a[data-id]').click(function () { var id = $(this).attr('data-id'); var domain = $(this).attr('data-domain'); $.ajax({ url: 'getdata& ...

Retrieve the values from multiple columns within a jqgrid row

Is it possible to retrieve both the first column value and the second column value from a jqgrid row? In my other program, I am currently using this code to obtain the first value of the row: $("#tblTallySheet").jqGrid('getGridParam', 'selr ...

Exploring the method of inserting an element into a nested array using JavaScript's ES6 features

Let's say I understand how to use the spread operator to add an element to a regular array in ES6. const arr = ["a","b"] const newArr = [...arr, "c"] This would result in ["a","b","c"] But when it comes to implementing this with a nested array, like ...

What causes the disparity in height between a textbox and the encompassing span element?

What causes the discrepancy in element heights when looking at the code below? <span id="spanner" style="margin:0;padding:0;border:0;outline:0;"><input type="text" /></span> If you check the height of the text box, it will be shown as 1 ...

"Troubleshooting: The Dropzone js code sample from the documentation

I am currently implementing a tutorial from the documentation provided by Dropzone.js. However, I seem to be encountering an issue as the example is not working correctly. Here is the structure that I currently have: Dropzone.options.myAwesomeDropzone = ...

Mastering text alignment with Three.js

I am trying to display text similar to the one shown in the image. Although I can manually insert line breaks into the text, I need a solution that can handle dynamic content without the need for manual adjustments. https://i.sstatic.net/0xb3K.png Below i ...

Using react-big-calendar exclusively for the month view

I need help customizing react-big-calendar to only show the month view and trigger a function when a date is selected. I want to remove all other functionalities related to week, day, agenda, and time display. Essentially, I just want to display the month- ...

Increase the thickness of a THREE.LineSegments to enhance its appearance

Currently, I'm working on enhancing the visualization of paths using Three.JS. Despite successfully incorporating numerous lines into the scene with the correct vertices and desired material, I am facing difficulty due to their lack of visibility. Is ...

Issue with inserting ContentPlaceHolder in script tags

In my ASP.Net Master Page, I encountered an issue: <script language="javascript" type="text/javascript"> <asp:ContentPlaceHolder ID="scriptContentHolder" runat="server"></asp:ContentPlaceHolder> </script> When attempt ...

Icons on Speed-Dial are not aligning to the center

I've been working on creating a Speed Dial feature for a web application, but I can't seem to get the icons to align properly in the Speed Dial menu. Despite following the instructions provided in https://vuetifyjs.com/en/components/floating-act ...

The Three.js Environment Experiencing Intense Tremors

Currently, I am immersed in a project that requires handling very large and very small distances utilizing three.js. Encountering an issue on the smaller side of the scene where the 'scene' begins to shake uncontrollably. Initially, I suspected ...

Calculating Three.js world coordinates based on mouse position using an orthographic camera

This question may have been asked before and answered, but despite following several suggestions (such as the one found here Mouse / Canvas X, Y to Three.js World X, Y, Z), I am still facing difficulties with my current situation. I have successfully impl ...

What is the process for turning off a TypeScript rule for a single line of code?

Dealing with Summernote as a jQuery plugin has been a bit of a struggle for me. I'm trying to modify the object without needing type definitions, but TypeScript keeps throwing errors my way. Even after attempting to delete certain keys, I still get th ...

Apps Script tutorial: copying hyperlinks between cells on different sheets

Is there a way to copy data from one sheet to another while keeping all the links active? Currently, when I use this formula, it only copies the text. I am unsure of what changes I need to make in order to copy all the data from the original sheet. functi ...

Comparing jQuery's [function] parameters to those in plain JavaScript

Throughout my coding projects, I have frequently utilized this javascript function... function toggleVisibility() { var args; args = showHideObjects.arguments; for(var i=0;i<args.length;i++) { if(document.getElementById(args[i])) { ...