screepers / typed-screeps-arena

MIT License
27 stars 14 forks source link

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

Open ngbrown opened 3 years ago

ngbrown commented 3 years ago

https://github.com/screepers/typed-screeps-arena/blob/75014a14c4ca0a5f1790b9aa55d7f7a45a4ad718/dist/game/utils.d.ts#L29-L32

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[]; 
thmsndk commented 3 years ago

Sounds like a good idea, I guess that is what the types for Screeps: World does based on the FIND_XX constant you give the find methods. Not sure AllGameObjects should contain GameObject though?

Feel free to make a PR for the relevant changes :)

lmik commented 2 years ago

coming back to this, @ngbrown have you tested this? i am not sure about possible side effects of arena specific types being included in your union 🤔

ngbrown commented 2 years ago

Hi @lmik. It did work last time I tried it, but that was back in the closed alpha...