Preserve Type When Using Object.entries
Solution 1:
This is related to questions like Why doesn't Object.keys()
return a keyof type in TypeScript?. The answer to both is that object types in TypeScript are not exact; values of object types are allowed to extra properties not known about by the compiler. This allows interface and class inheritance, which is very useful. But it can lead to confusion.
For example, if I have a value nameHaver
of type {name: string}
, I know it has a name
property, but I don't know that it only has a name
property. So I can't say that Object.entries(nameHaver)
will be Array<["name", string]>
:
interfaceNameHaver { name: string }
declareconstnameHaver: NameHaver;
constentries: Array<["name", string]> = Object.entries(nameHaver); // error here: why?
entries.map(([k, v]) => v.toUpperCase());
What if nameHaver
has more than just a name
property, as in:
interfaceNameHaver { name: string }
classPersonimplementsNameHaver { constructor(public name: string, public age: number) { } }
constnameHaver: NameHaver = newPerson("Alice", 35);
constentries: Array<["name", string]> = Object.entries(nameHaver); // error here: ohhh
entries.map(([k, v]) => v.toUpperCase()); // explodes at runtime!
Oops. We assumed that nameHaver
's values were always string
, but one is a number
, which will not be happy with toUpperCase()
. The only safe thing to assume that Object.entries()
produces is Array<[string, unknown]>
(although the standard library uses Array<[string, any]>
instead).
So what can we do? Well, if you happen to know and are absolutely sure that a value has only the keys known about by the compiler, then you can write your own typing for Object.entries()
and use that instead... and you need to be very careful with it. Here's one possible typing:
type Entries<T>={[K in keyof T]:[K,T[K]]}[keyof T];
function ObjectEntries<T extends object>(t:T): Entries<T>[]{return Object.entries(t) as any;
}
The as any
is a type assertion that suppresses the normal complaint about Object.entries()
. The type Entries<T>
is a mapped type that we immediately look up to produce a union of the known entries:
const entries = ObjectEntries(nameHaver);
// const entries: ["name", string][]
That is the same type I manually wrote before for entries
. If you use ObjectEntries
instead of Object.entries
in your code, it should "fix" your issue. But do keep in mind you are relying on the fact that the object whose entries you are iterating has no unknown extra properties. If it ever becomes the case that someone adds an extra property of a non-number[]
type to unpassable_tiles
, you might have a problem at runtime.
Okay, hope that helps; good luck!
Solution 2:
@jcalz's excellent answer explains why what you are trying to do is so tricky. His approach could work if you want to keep your underlying schemas and JSON the same. But I will point out that you can sidestep the entire problem just by structuring your data differently. I think that will make your developer experience, as well as the clarify of what your data is, better.
One of the fundamental problems you're having is that you're trying to treat a map of key: value
pairs as, in your case, some sort of list of impassable tiles. But it is inherently unwieldy and confusing to work with Object.entries
just to get at your impassable tile types.
Why not define ImpassableTile
as a type, and the list of impassable tiles as an array of that type? That better matches, conceptually, what the data actually represents. It also sidesteps Object.entries
and its difficulties entirely, and makes iterating over the data more simple and clear.
// levelData.tsimport levelJSON from"./levelJSON.json";
interface ILevelJSON {
[key: string]: Level;
}
interfaceLevel {
tiles: Tiles;
}
exporttypeUnpassableType = "rock" | "tree";
typeUnpassableTile = {
type: UnpassableType;
position: number[];
};
interfaceTiles {
unpassable_tiles: UnpassableTile[];
}
exportdefault levelJSON as ILevelJSON;
To properly match the new interface, you'd need to modify levelJSON.json as well. But note that it's a lot cleaner and you'd don't need to define empty arrays for rocks or trees in level_2, those are simply absent:
{"level_1":{"tiles":{"unpassable_tiles":[{"type":"rock","position":[0,0]},{"type":"rock","position":[2,0]},{"type":"tree","position":[2,2]}]}},"level_2":{"tiles":{"unpassable_tiles":[]}}}
Now you can very easily map over your impassable tiles, their types, and associated position data, all while retaining full type inference and safety. And it looks a lot more clear and understandable IMO.
// App.tsxconstUnpassableTileComponents = React.useMemo(() => {
return levelData[`level_1`].tiles.unpassable_tiles.map(
({ type, position: [leftPos, topPos] }) => (
<UnpassableTilekey={`level_1_${type}_${leftPos}_${topPos}`}
leftPos={leftPos}topPos={topPos}tileType={type}
/>
)
);
}, []);
https://codesandbox.io/s/goofy-snyder-u9x60?file=/src/App.tsx
You can further extend this philosophy to how you structure your Levels and their interfaces. Why not have levelJSON
be an array of Level
objects, each with a name and set of tiles?
interfaceTiles {
unpassable_tiles: UnpassableTile[];
}
interfaceLevel {
name: string;
tiles: Tiles;
}
exporttypeUnpassableType = "rock" | "tree";
typeUnpassableTile = {
type: UnpassableType;
position: number[];
};
Your corresponding data would look a lot cleaner:
[{"name":"level_1","tiles":{"unpassable_tiles":[{"type":"rock","position":[0,0]},{"type":"rock","position":[2,0]},{"type":"tree","position":[2,2]}]}},{"name":"level_2","tiles":{"unpassable_tiles":[]}}]
And iterating over it would become even more clear:
const level = levelData[0];
constUnpassableTileComponents = React.useMemo(() => {
return level.tiles.unpassable_tiles.map(
({ type, position: [leftPos, topPos] }) => (
<UnpassableTilekey={`${level.name}_${type}_${leftPos}_${topPos}`}
leftPos={leftPos}topPos={topPos}tileType={type}
/>
)
);
}, [level]);
https://codesandbox.io/s/hopeful-grass-dnohi?file=/src/App.tsx
Post a Comment for "Preserve Type When Using Object.entries"