Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property does not exist on type 'T' - Generic problems

I have a util that takes an array and a predicate to perform a filtration of the array, however after using my custom type for the predicate I am getting an error stating

property 'name' does not exist on type 'T'

I thought that the generic property type T would have accepted anything?

Am I missing something obvious?

Array.ts

export type arrayPredicate = <T>(arg: T) => boolean;

ArrayUtil

static filterArray<T>(array: T[], arrayPred: arrayPredicate): T {
    const key =  Object.keys(array).find(obj => arrayPred(array[obj]));
    return array[key];
  }

Usage in test

const array = [
  {
    'name': 'object-1',
    'id': 1
  },
  {
    'name': 'object-2',
    'id': 2
  }
];

it(... , () => {

  // I get red squigglies under '.name'

  const myObj = ArrayUtils.filterArray(exceptionalStatuses, 
                                          (status => status.name === findStatus));

  ...

});

Of course, changing

like image 680
physicsboy Avatar asked Oct 18 '18 09:10

physicsboy


2 Answers

Change your arrayPredicate declaration as shown below.

export type arrayPredicate<T> = (arg: T) => boolean;

class ArrayUtils {
    static filterArray<T>(array: T[], arrayPred: arrayPredicate<T>): T {
    const key =  Object.keys(array).find(obj => arrayPred(array[obj]));
    return array[key];
  }
}

Since you are not declaring parameter in type for arrayPredicate, it is assumed to be empty object.

Here is working example,

TypeScript example

like image 111
Akash Kava Avatar answered Sep 30 '22 17:09

Akash Kava


Need to add a type for your array for exmaple lets sat type of the array is SampleType[]. Then is should be

const array: SampleType[] = [
  {
    'name': 'object-1',
    'id': 1
  },
  {
    'name': 'object-2',
    'id': 2
  }
];

Then pass that type to the generic function

 ArrayUtils.filterArray<SampleType>(exceptionalStatuses, (status: SampleType => status.name === findStatus));

SampleType should be

export class SampleType{
  name: string,
  id: string
}
like image 44
Sachila Ranawaka Avatar answered Sep 30 '22 15:09

Sachila Ranawaka