Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

296
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda