0

I'm trying to make a function that takes an object as an argument and returns a random property of the object. This question provides an answer- but Typescript doesn't like that I'm using a string to index an object.

    const randomElement = (obj: object) => {
    var keys = Object.keys(obj);
    return obj[keys[keys.length * Math.random() << 0]];
  
    }

In my project this function will always accept the same type of object (so I could use an interface), but I want to know if it's possible to make the function more flexible.

As requested here is my TS config file:

  {
  "compilerOptions": {
    "target": "es6",
    "lib": ["es5", "es6", "dom", "dom.iterable"],
    "strictNullChecks": false,
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src", "vite.config.ts"]
  }

The above code produces the following errors:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  No index signature with a parameter of type 'string' was found on type '{}'.ts(7053)
Thomas Franklin
  • 574
  • 4
  • 14
  • If I look at that code [in an IDE](https://tsplay.dev/mAj3vW) the only problem I see is that you haven't given a type to `obj`, so it's implicitly `any`, and that can be fixed by annotating it as `any` explicitly. So your issue "doesn't like that I'm using a string to index an object" is not reproducible. Could you provide a [mre] that clearly demonstrates your problem? – jcalz Feb 26 '22 at 14:52
  • please share also your tsconfig – Meddah Abdallah Feb 26 '22 at 14:54
  • Does [this approach](https://tsplay.dev/w160AN) meet your needs? – jcalz Feb 26 '22 at 20:56
  • It does. For anyone else looking for the answer this is it – Thomas Franklin Feb 26 '22 at 22:57

1 Answers1

0

Have you tried casting it into number like this

Number(keys.length * Math.random() << 0)

You also can type your obj as follows

function (obj: [key: string]: any)

<!-- begin snippet: js hide: false console: true babel: false -->
Meddah Abdallah
  • 654
  • 1
  • 7
  • 25