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

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

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