Skip to content

Commit

Permalink
Stronger typing for Archetype (#102)
Browse files Browse the repository at this point in the history
* Stronger typing for Archetype

* Add changeset

Co-authored-by: Hendrik Mans <hendrik@mans.de>
  • Loading branch information
benwest and hmans committed Aug 2, 2022
1 parent 65d2b77 commit 1cee12c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/cold-monkeys-thank.md
@@ -0,0 +1,5 @@
---
"miniplex": patch
---

Typing improvements, thanks to @benwest.
15 changes: 11 additions & 4 deletions packages/miniplex/src/Archetype.ts
Expand Up @@ -8,26 +8,33 @@ import { ComponentName, EntityWith, IEntity } from "./World"
*/
export type Query<T extends IEntity> = ComponentName<T>[]

export type ArchetypeEntity<
TEntity extends IEntity,
TQuery extends Query<TEntity> = Query<TEntity>
> = EntityWith<TEntity, TQuery[number]>

export class Archetype<
TEntity extends IEntity,
TQuery extends Query<TEntity> = Query<TEntity>
> {
/** A list of entities belonging to this archetype. */
public entities = new Array<
EntityWith<RegisteredEntity<TEntity>, TQuery[number]>
ArchetypeEntity<RegisteredEntity<TEntity>, TQuery>
>()

get [Symbol.iterator]() {
return this.entities[Symbol.iterator]
}

/** Returns the first entity within this archetype. */
get first() {
get first(): ArchetypeEntity<RegisteredEntity<TEntity>, TQuery> | null {
return this.entities[0] || null
}

/** Listeners on this event are invoked when an entity is added to this archetype's index. */
public onEntityAdded = new Signal<RegisteredEntity<TEntity>>()
public onEntityAdded = new Signal<
ArchetypeEntity<RegisteredEntity<TEntity>, TQuery>
>()

/** Listeners on this event are invoked when an entity is removed from this archetype's index. */
public onEntityRemoved = new Signal<RegisteredEntity<TEntity>>()
Expand All @@ -44,7 +51,7 @@ export class Archetype<
/* If the entity should be indexed, but isn't, add it. */
if (shouldBeIndexed && !isIndexed) {
entity.__miniplex.archetypes.push(this)
this.entities.push(entity as any)
this.entities.push(entity)
this.onEntityAdded.emit(entity)
return
}
Expand Down
7 changes: 5 additions & 2 deletions packages/miniplex/src/util/entityIsArchetype.ts
@@ -1,6 +1,9 @@
import { Query } from "../Archetype"
import { Query, ArchetypeEntity } from "../Archetype"
import { IEntity } from "../World"

export function entityIsArchetype<T extends IEntity>(entity: T, query: Query<T>) {
export function entityIsArchetype<
TEntity extends IEntity,
TQuery extends Query<TEntity>
>(entity: TEntity, query: TQuery): entity is ArchetypeEntity<TEntity, TQuery> {
return query.every((name) => name in entity)
}

0 comments on commit 1cee12c

Please sign in to comment.