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
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,
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
}
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.