I have a generic component that accepts an array of object of type T and a string that is a key of T. The purpose of this component is to filter the array of objects based on a character in the alphabet but to do so I need the given input key to have a string value. Here's some sample code:
@Input() data: T[];
@Input() key: keyof T;
function filterByChar(char: string) {
return this.data.filter(el => el[this.key] === char);
}
This does not work because el[this.key] might not be a string.
Is it possible to restrict key to be a key of object T that have string values only?
Here's a link to stackblitz example
EDIT:
The @Input() key has a restriction, only keys of T are allowed. I want to allow only keys of T that have string values (at compile time if possible).
EDIT 2: Suppose the actual type of T is something like this:
interface Person {
id: number;
name: string;
email: string;
address: Address;
}
When you call my component
<app-filter-by [data]="someData" [key]="XXXX"></app-filter-by>
I want to enforce that only keys of T of type string are allowed. In this example only name and email should be allowed.
try some of these:
return this.data.filter(el => (el as any)[this.key] === char);
return this.data.filter(el => (($any)el)[this.key] === char);
return this.data.filter(el => ( el[this.key] as unknown as keyof T === char ));