Sample JSON
{
"files": {
"group1": {
"subgroup1": ["file1", "file2"]
},
"group2": {
"subgroup2": ["file3", "file4"],
"subgroup3": ["file5"]
}
}
}
I am trying to build a function that gives me a random file, given the group and subgroup names
Try 1
import data from "./data.json";
function getRandomImage(group: string, subgroup: string) {
const files = data.files[group][subgroup];
return files[Math.floor(Math.random() * files.length)];
}
The above code gives me this error
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ group1: { subgroup1: string[]; }; group2: { subgroup2: string[]; subgroup3: string[]; }; }'. No index signature with a parameter of type 'string' was found on type '{ group1: { subgroup1: string[]; }; group2: { subgroup2: string[]; subgroup3: string[]; }; }'.
Try 2
function getRandomImage(data: any, group: string, subgroup: string) {
const files = data.files[group][subgroup];
return files[Math.floor(Math.random() * files.length)];
}
i tried passing data also with any type, but that gives error
Unexpected any. Specify a different type.
Try 3
type groupType = keyof typeof data.files;
type subGroupType = keyof typeof data.files[groupType];
function getRandomImage(group: groupType, subgroup: subGroupType) {
const files = data.files[group][subgroup];
return files[Math.floor(Math.random() * files.length)];
}
that gives me error
Property 'length' does not exist on type 'never'.
I am very new to typescript (coming from python), so this has been a big hassle.. please help me out.