Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

289
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda