Utilize generic types within methods in TypeScript

Here is a snippet of code I'm working on in TypeScript:

public static sortByProperty<T>( array: T[], prop: string ): void 
{
      var availProps: string[] = Object.getOwnPropertyNames( T ); // or something typeof T, anyway I got error

      if(availProps.length>0 && availProps.indexOf(prop) > -1){
          return array.Sort(function(a, b) {
               var aItem = a[prop];
               var bItem = b[prop]; 
               return ((aItem < bItem ) ? -1 : ((aItem > bItem ) ? 1 : 0));
          });
      }
}

In my code, I want to utilize it like this:

Test.sortByProperty<MyObject>(arrayOf_MyObject, "APropertyName");

However, I encountered an error stating that T is unknown.

Answer №1

Have you considered leveraging the compiler for property checking? By typing your prop parameter as keyof T, you can ensure that the compiler enforces the correct type.

class Example {
  public static sortDataByProperty<T>(array: T[], prop: keyof T): void {

      array.sort(function (a, b) {
        var aProp = a[prop];
        var bProp = b[prop];
        return ((aProp < bProp) ? -1 : ((aProp > bProp) ? 1 : 0));
      });
  }
}

interface CustomObject {
  value: string
}

Example.sortDataByProperty<CustomObject>([{value: "abc"}], "value"); // Success
Example.sortDataByProperty<CustomObject>([{value: "xyz"}], "invalidprop"); // Error

To address your initial query about manually checking properties, you can use Object.getOwnPropertyNames by passing a value like

Object.getOwnPropertyNames(array[0])
assuming there is at least one item in the array.

Answer №2

Remember to pass array element when using Object.getOwnPropertyNames(), not T.

In Javascript, T is no longer accessible once it has been compiled. It is specifically for Typescript. Instead, try using

Object.getOwnPropertyNames(array[0])
to iterate through all properties of your T object.

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

Setting the default value for a dropdown in Angular 2 using Kendo UI

I'm currently facing an issue with creating a dropdownlist using Kendo UI. The problem arises when I try to set a default selected value upon loading the screen. Referring to their documentation, my code is structured like this: HTML: <kendo-drop ...

Difficulty transferring function to child element

It seems like I may be overlooking something simple due to exhaustion, but I'm hoping someone can assist me! I have a function that the parent component inherits from the provider, and I am trying to pass it to the child as shown below: console.log(t ...

Tips for enhancing the efficiency of a three.js environment within Gatsby.js or react:

I am dealing with a straightforward three.js scene that is rendered using an useEffect hook. The scene loads a model using GLTFLoader(). On the page, there are three event listeners triggered on load. One calculates the browser's inner height, anothe ...

Create a loop that depends on the user's ID

Utilizing node, express, and swig, my goal is to create a loop based on the currentUser local variable. Although I have managed to get the loop working, it currently displays results for every user. Below is the loop I am using: {% for ap in aps %} ...

injecting a variable from the configuration service into a TypeScript decorator

I am interested in setting up a scheduled task for my NestJs application to run at regular intervals. I found information on how to use intervals in the NestJs documentation. Since my application uses configuration files, I want to keep the interval value ...

Is there a way to calculate the word frequency in my text using plain JavaScript?

Welcome to the text entry section: https://i.sstatic.net/VlBvt.png After clicking on the COUNT button, it will direct you to this page: https://i.sstatic.net/sqKWc.png I can see my entered text and word count displayed. Now I'm curious, how can I ...

Is the issue of res.locals not being properly propagated to all requests in Express middleware persisting?

Currently, I am building a web app using express, node, and handlebars with passport as the authentication library. In an attempt to customize the navigation bar based on the user's state, I am trying to set a variable in res.locals. However, I am enc ...

Changing Page Content with Ajax Post-Redirect Pattern

Just had a quick question. Can the redirected page be affected by ajax's success function? The code will provide a better explanation. $.ajax({ type: "POST", url: "/admin/done", data: { ...

The JSX component cannot utilize 'Home' when working with React and TypeScript

I am a beginner in using React and TypeScript, and I want to retrieve data from an API and display it in a table using TypeScript and React. My project consists of two files: Home.tsx and App.tsx. The primary code that interacts with the API is located in ...

The utilization of `ngSwitch` in Angular for managing and displaying

I am brand new to Angular and I'm attempting to implement Form Validation within a SwitchCase scenario. In the SwitchCase 0, there is a form that I want to submit while simultaneously transitioning the view to SwitchCase 1. The Form Validation is fun ...

Extracting data from a JSON array using JavaScript: A guide

I'm encountering an issue with a PHP function that returns an array to JavaScript. Here's how the code looks: $data['first'] = 10; $data['second'] = 20; echo json_encode($data); Upon receiving the value in JavaS ...

What is the best way to retrieve information from a function that returns an AJAX GET JSON response?

There is a function in my code that uses ajax to return JSON data: function fetchTagData(fileName) { $.ajax({ type: "GET", dataType: "json", url: "/tags/find-tag/"+fileName.tag, success: function(data){ con ...

Angular throws a 404 error when making a JSONP http request

I've been incorporating Mailchimp integration into an Angular application. For using it in pure JS, I retrieved the code from the embedded form on the Mailchimp site: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ...

Having trouble with the Semantic UI popup not showing div content correctly? Need to display table row data as well? Let's troub

Having trouble with this semantic-ui code popup error. Can anyone provide a solution? $(document).on('click', 'table td', function() { $(this) .popup({ popup: $('.custom.popup') }); }) ...

Click on the button to send the input field

Below you'll find an input field and a button: <input id="pac-input" class="controls" type="text" placeholder="Search! e.g. Pizza, Pharmacy, Post office"> <button id="new" class="btn btn-success">Submit</button> Currently, when te ...

Ways to navigate to a different page while displaying an alert message?

Desperately seeking assistance with redirecting to another page and then triggering an alert("HELLO") once the new page is loaded. I have attempted the following approach: $.load(path, function() { alert.log("HELLO"); }); But using window.location o ...

Retrieving data from MongoDB and presenting it neatly in Bootstrap cards

I have successfully retrieved data from MongoDB and displayed it in Bootstrap 5 cards. However, I am facing an issue where all the cards are appearing in a single row if there are multiple entries in the database. What I want to achieve is to utilize the ...

Efficient - Managing numerous database connections

I am currently working on a project using node.js and I have created a login form where users need to select the database they want to connect to. However, I am uncertain about how to establish a connection with the selected database. Is there a way for m ...

Sending a result back to a Silverlight user control from a slightly intricate JavaScript function

I am working on a Silverlight user control that contains a textbox and a button. Within this Silverlight page, there can be multiple instances of these user controls. My goal is to have a JavaScript function trigger when the button is clicked. This functi ...

Transferring the value of a variable from Block to Global Scope in FIRESTORE

I'm currently working on an App in Firebase, utilizing FireStore as my primary Database. Below is a snippet of code where I define a variable order and set it to a value of 1. Afterwards, I update the value to 4 and use console.log to verify. Everyt ...