Better typings for Lookup

This commit is contained in:
Tangent Wantwight 2020-01-16 00:03:24 -05:00
parent 8434e7046c
commit a080dabc67
2 changed files with 12 additions and 43 deletions

View File

@ -77,45 +77,14 @@ export function Remove<DATA extends Data>(data: DATA, [id, generation]: Id, stat
}
// Ergonomic Lookup typings
export function Lookup<
DATA extends Data,
A extends keyof DATA,
> (
data: DATA,
id: Id,
a: A,
): [
DATA[A][number] | null
];
export function Lookup<
DATA extends Data,
A extends keyof DATA,
B extends keyof DATA,
> (
data: DATA,
id: Id,
a: A,
b: B,
): [
DATA[A][number] | null,
DATA[B][number] | null
];
export function Lookup<
DATA extends Data,
A extends keyof DATA,
B extends keyof DATA,
C extends keyof DATA,
> (
data: DATA,
id: Id,
a: A,
b: B,
c: C,
): [
DATA[A][number] | null,
DATA[B][number] | null,
DATA[C][number]
];
type ItemType<S> = S extends Record<number, infer T> ? T : never;
type StoreType<DATA extends Data, K> = K extends keyof DATA ? ItemType<DATA[K]> : never;
type StoreTypes<DATA extends Data, K extends (keyof DATA)[]> = {
[I in keyof K]: StoreType<DATA, K[I]>;
};
type MaybeStoreTypes<DATA extends Data, K extends (keyof DATA)[]> = {
[I in keyof K]: StoreType<DATA, K[I]> | null;
};
/**
* Look up components that may or may not exist for an entity
@ -124,7 +93,7 @@ export function Lookup<
* @param components names of components to look for
* @returns the cooresponding components, with unfound ones replaced by nulls
*/
export function Lookup<DATA extends Data, K extends keyof DATA>(data: DATA, [id, generation]: Id, ...components: K[]): ({} | null)[] {
export function Lookup<DATA extends Data, K extends (keyof DATA)[]>(data: DATA, [id, generation]: Id, ...components: K): MaybeStoreTypes<DATA, K> {
const entity = data.entity[id];
// inactive entities are fine to lookup, but dead ones are not
if(entity && entity.generation == generation && entity.alive != Liveness.DEAD) {
@ -135,9 +104,9 @@ export function Lookup<DATA extends Data, K extends keyof DATA>(data: DATA, [id,
} else {
return null;
}
});
}) as MaybeStoreTypes<DATA, K>;
} else {
return components.map(() => null);
return components.map(() => null) as MaybeStoreTypes<DATA, K>;
}
}

View File

@ -144,7 +144,7 @@ export class LoopTest {
DumbMotion(this.data, interval);
const [triangleDebug] = Lookup(this.data, triangleId, "renderBounds");
(triangleDebug as RenderBounds).color = "#d40";
if(triangleDebug) triangleDebug.color = "#d40";
FindCollisions(this.data, 500, (className, sourceId, targetId) => {
switch(className) {