I'm fairly new to TypeScript, so I'm in the process of upgrading my old projects to utilize it.
However, I'm not sure how to preserve the correct Type when calling Object.entries on some data.
As an example:
Level.tsx:
const UnpassableTileComponents = useMemo(() =>
Object.entries(levelData[`level_${gameLevel}`].tiles.unpassable_tiles).map(([tileType, tiles]) => (
tiles.map(([leftPos, topPos], index) => (
<UnpassableTile
key={`${tileType}_${index}`}
leftPos={leftPos * 40}
topPos={topPos * 40}
tileType={tileType}
/>
))
)
).flat(), [gameLevel])
levelData.tsx:
import levelJSON from "./levelJSON.json";
interface ILevelJSON {
[key: string]: Level;
}
interface Level {
tiles: Tiles;
}
interface Tiles {
unpassable_tiles: UnpassableTiles;
}
interface UnpassableTiles {
rock: Array<number[]>;
tree: Array<number[]>;
}
export default levelJSON as ILevelJSON;
levelJSON.json:
{
"level_1": {
"tiles": {
"unpassable_tiles": {
"rock": [[0, 0]],
"tree": [[2, 0]]
}
}
},
"level_2": {
"tiles": {
"unpassable_tiles": {
"rock": [[]],
"tree": [[]]
}
}
}
}
In the case of the above, tiles represents an Array of arrays, each with two numbers. Therefore, [leftPos, topPos] should both be typed as number. However, in Level.tsx, they have properties of any. I could get my desired result with the following:
const UnpassableTileComponents = useMemo(() =>
Object.entries(levelData[`level_${gameLevel}`].tiles.unpassable_tiles).map(([tileType, tiles]) => (
tiles.map(([leftPos, topPos] : number[], index: number) => (
<UnpassableTile
key={`${tileType}_${index}`}
leftPos={leftPos * 40}
topPos={topPos * 40}
tileType={tileType}
/>
))
But shouldn't number[] be inferred anyways?
Any advice would be appreciated.