#How to enforce an array to have all keys of a generic type?
10 messages · Page 1 of 1 (latest)
Depending on what you're doing it might make sense to work the other direction:
const arr = ["a", "b", "c"] as const
type Foo = Record<(typeof arr)[number], number>;
This still doesn't prevent duplicates but does mean that Foo won't have extra properties that aren't in the array.
You couldn't generate a tuple's signature in the same way? LIke Mapped types in objects?
LIke for example,
type Foo<Source> = {
[Property in keyof Source]: string;
};
this works for objects using mapped types, there's no way to make a mapped tuple I guess is the question
Unions aren't ordered so converting an unordered union into an ordered tuple is at the least going to involve some dark magic
Gotcha. I'll leave my code how it is now then.
Right now I have a type which enforces that a callback function be written for all keys:
export type EntityUpdateCallbacks<Source extends object> = {
[Property in keyof Source]-?: [order: number, callback: () => void];
};
and I use this here:
export type Entity<T> = {
updateCallbacks: EntityUpdateCallbacks<T>;
};
but the problem I had is that I realized I need to call the callbacks in a specific order. But I also like that TS can enforce that a callback is defined for each key, because my keys will change during development and it's nice to have it tell you where you need to change the code.
Right now I'm doing this to order them, and I was just wondering if there's a cleaner way
const callbacks = Object.entries(entity.updateCallbacks)
.map((entry) => ({
key: entry[0],
order: entry[1][0],
callback: entry[1][1],
}))
.sort((a, b) => a.order - b.order);
It might be possible; I think that there are some tricks to do that kinda stuff; but I don't know it off-hand, and would rather stick to "light magic" techniques
Yeah, I guess that's tricky. Technically, you could probably get away with just calling them in the order that they're defined - nowadays Javascript does guarantee iteration order of object properties.
Oh, I didn't realize JS guarantees key insertion order. I kind of feel a bit foolish now haha