Imagine having the interface below:
interface ITest {
a: number;
b: string;
Now, I am looking to create a function with similar functionality:
public filterByPropertyValue<T>(array: T[], key: keyof T, value: typeof ????) {
return array.filter(e => e[key] === value)
}
Specifically, the examples provided should not work:
const array: ITest[] = [ {a: 1, b: 'some'}, {a: 2, b: 'value'}];
filterByPropertyValue<ITest>(array, 'a', 'abc') // because 'a' is of type number
filterByPropertyValue<ITest>>(array, 'b', 15) // because 'b' is of type string
However, the following examples should be successful:
const array: ITest[] = [ {a: 1, b: 'some'}, {a: 2, b: 'value'}];
filterByPropertyValue<ITest>(array, 'a', 1) // returns array[0]
filterByPropertyValue<ITest>(array, 'b', 'value') // returns array[1]
filterByPropertyValue<ITest>(array, 'b', 'foobar') // returns an empty array
I experimented with different combinations of typeof
and keyof
, but I struggled to find a solution when using typeof
on a keyof
variable.