Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
I want to allow, as an @Input of a component, only keys that have string values

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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 ));



about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!