Currently in the process of learning TypeScript, so please bear with me if I am not describing this accurately.
I have a function that retrieves some data and returns a nested object. I then iterate over this object using forEach method. Although I have defined types for each value in the object, I am encountering an error:
Error: Argument of type '(value: RaceInfo) => void' is not compatible with parameter of type '(value: unknown, index: number, array: unknown[]) => void'. The types of parameters 'value' and 'value' do not match. Type 'unknown' cannot be assigned to type 'RaceInfo'.ts(2345)
Please refer to the code snippet below:
interface Selection {
date: string;
time: string;
venue: string;
}
interface RaceInfo {
codes: {
race_sc: string;
};
details: {
venue: string;
};
}
export default async function getSC(selection: Selection) {
let sc;
await fetch(`URL`,{method: "GET",})
.then((response) => response.json())
.then((data) => {
if (data.success) {
Object.values(data.races).forEach((value: RaceInfo) => {
if (
value.codes.race_sc.slice(-4) === selection.time &&
value.details.venue === selection.venue
) {
sc = value.codes.race_sc;
}
});
} else {
console.log("Could not fetch the races");
}
})
.catch((error) => {
console.log("Error:", error);
});
return sc;
}
I was able to resolve this issue by modifying the loop code itself, which works perfectly fine. However, I am unsure if this approach aligns with strict TypeScript standards since I did not have to specify types/interfaces for the returned object. Is this considered an acceptable practice?
for (const key of Object.keys(data.races)) {
const value = data.races[key];
if (
value.codes.race_sc.slice(-4) === selection.time &&
value.details.venue === selection.venue
) {
sc = value.codes.race_sc;
}
}