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

638
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

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());

over 4 years ago · Santiago Trujillo 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!