Skip to content

Should getObjects() return a union of concrete types? #7

Open
@ngbrown

Description

@ngbrown

/**
* Get all objects in the game.
*/
export function getObjects(): GameObject[];

The current return type of GameObject[] doesn't avail its self of being able to discriminate into specific objects. For example, I would expect the following to work:

  for (const o of getObjects()) {
    if ('body' in o && o.my) {
      o.attack(enemy)
    }
  }

But it doesn't because TypeScript doesn't assume that an array of a base type could be any implementation of it. I propose that a union type be created of all the items that could be returned and getObjects() returns that type of array.

type AllGameObjects =
  | GameObject
  | Creep
  | Structure
  | OwnedStructure
  | StructureTower
  | StructureSpawn
  | StructureContainer
  | StructureWall
  | StructureExtension
  | StructureRampart
  | ConstructionSite
  | Resource
  | Source
  | Flag
  | ScoreCollector;
export function getObjects(): AllGameObjects[]; 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions