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

182
Visualizações
How do I define a generic variable in Typescript?

Consider two Typescript interfaces A and B:

interface A {
    propertyA: string;
    propertyB: string;
    propertyC: string;
    propertyD: string;
    propertyE: string;    
}

interface B {
    propertyF: string;
    propertyG: string;
    propertyH: string;
    propertyI: string;
    propertyJ: string;
    propertyK: string;    
}

I want to define a constant, a Key-Value Pair, that pairs a string value with either interface A or interface B.

const keyValuePair: { [key: string]: A | B} = {};

Then, a function would pass in a generic value, T, indicative of what the value in the Key-Value Pair would be, and I would return the Key-Value Pair with the appropriate value object:

export async function getKeyValuePair<T>(keyId: string): Promise<T> {
    if (keyValuePair<T>[keyId]) {
        return keyValuePair<T>[keyId];
    }
}

Obviously. The above will not work. But, how can I get it to work? If I was just doing interface A, I would do the following and it would work fine:

const keyValuePair: { [key: string]: A} = {};

export async function getKeyValuePair(keyId: string): Promise<A> {
    if (keyValuePair[keyId]) {
        return keyValuePair[keyId];
    }
}

I realize I could do the following:

const keyValuePair: { [key: string]: any} = {};

But I really want something better and would like to avoid use of "any" if possible. How would I do this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you goal is to retrieve an object and cast it to a certain type you could do this:

export async function getKeyValuePair<T>(keyId: keyof T): Promise<T> {
    return keyValuePair[keyId] as unknown as T;
}

So you could use like this:

getKeyValuePair<B>('propertyF');
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