I m fairly new to TypeScript, so I m in the process of upgrading my old projects to utilize it.
然而,我不知道在发出反对时如何保持正确的类型。 一些数据条目。
例如:
<>水平:
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?
任何建议都会得到赞赏。