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,
TypeScript 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With