Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stronger typing for Archetype #102

Merged
merged 2 commits into from Aug 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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,22 +8,29 @@ 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>
>()

/** 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 @@ -40,7 +47,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)
}