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)