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

304
Vistas
Get random element of dictionary in TypeScript?

I am trying to implement code that will return me a random element of a dictionary in TypeScript. So far, I've tried this:

dict = {
    0: "example 1",
    1: "example 2",
    2: "example 3"
  }

randomGen() { 
    var num = Math.floor(Math.random() * (3));
    console.log(this.dict[num])
  }

However this is throwing me an error:

Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{ 0: string; 1: string; 2: string; }

Is there a way around this? How can I randomly select an element from my dictionary?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here you go. I use the dictionary you created and randomly select a number based on the length of the dictionary (which are your keys). Then return the value of the random key.

Here is for Typescript (test in https://www.typescriptlang.org/play):

var dict: {[key: number]: string} = {
    0: "example 1",
    1: "example 2",
    2: "example 3"
  }

function randomGen() { 
    var value = dict[Math.floor(Math.random() * Object.keys(dict).length)];
    return value;
  }
 
console.log(randomGen());

And below is for basic JavaScript:

var dict = {
    0: "example 1",
    1: "example 2",
    2: "example 3"
  }

function randomGen() { 
    var value = dict[Math.floor(Math.random() * Object.keys(dict).length)];
    return value;
  }
 
console.log(randomGen());

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