简体   繁体   中英

Use generic type in method TypeScript

In typescript, I have the following code:

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));
          });
      }
}

and I want to use like

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

I got error that T is unknown

Why not let the compiler do the property checking for you. You can type your prop parameter as keyof T and the compiler will enforce it.

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

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

interface MyObject {
  test: string
}

Test.sortByProperty<MyObject>([{test: "something"}], "test"); // OK
Test.sortByProperty<MyObject>([{test: "something"}], "notaprop"); // Error

To answer your original question if you want to check the property yourself, you have to pass a value to Object.getOwnPropertyNames something like: Object.getOwnPropertyNames(array[0]) assuming your array has at least one item.

You have to pass array element to Object.getOwnPropertyNames() not T.

T isn't available in Javascript anymore once it's compiled. It's only for Typescript. You can use Object.getOwnPropertyNames(array[0]) which should iterate trough all properties of your T object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM