Get random element of dictionary in TypeScript?

Viewed 380

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?

1 Answers

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

Related