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

184
Views
¿Cómo defino una variable genérica en Typescript?

Considere dos interfaces Typescript A y 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; }

Quiero definir una constante, un par clave-valor, que empareja un valor de cadena con la interfaz A o la interfaz B.

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

Luego, una función pasaría un valor genérico, T, indicativo de cuál sería el valor en el par clave-valor, y devolvería el par clave-valor con el objeto de valor apropiado:

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

Obviamente. Lo anterior no funcionará. Pero, ¿cómo puedo hacer que funcione? Si solo estuviera haciendo la interfaz A, haría lo siguiente y funcionaría bien:

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

Me doy cuenta de que podría hacer lo siguiente:

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

Pero realmente quiero algo mejor y me gustaría evitar el uso de "cualquiera" si es posible. ¿Cómo haría esto?

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

0

Si su objetivo es recuperar un objeto y convertirlo en un tipo determinado, puede hacer esto:

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

Así que podrías usar así:

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