Coder Social home page Coder Social logo

typed-screeps's Introduction

typed-screeps

Strong TypeScript declarations for the game Screeps: World.

Github action npm

Installation

The type definitions are published on DefinitelyTyped. To install them, run the following.

# npm
npm install @types/screeps

# yarn
yarn add @types/screeps

This repo has more activity and is considerably more up-to-date.

Breaking Changes:

  • Memory is typed by default. The added typings are:

    • CreepMemory
    • FlagMemory
    • SpawnMemory
    • RoomMemory

    If you like the idea of typed memory, but aren't ready to just jump fully in, you only need to make sure you define an interface for the above four types. Then you can extend them at a later time.

    Example:

    interface CreepMemory { [name: string]: any };
    interface FlagMemory { [name: string]: any };
    interface SpawnMemory { [name: string]: any };
    interface RoomMemory { [name: string]: any };

    If you don't want to add types to the global Memory object, you will need to add the following interface along with the four above.

    Example:

    interface Memory { [key: string]: any };
  • Any place in code that uses a constant (ex STRUCTURE_EXTENSION or FIND_MY_SPAWNS is now constrained to use literal types. Here is the list of the new types:

    BodyPartConstant
    BuildableStructureConstant (this is a subset of StructureConstant)
    StructureConstant
    FindConstant
    LookConstant
    DirectionConstant
    ResourceConstant
    MineralConstant (this is a subset of ResourceConstant)
    ColorConstant
    ScreepsReturnCode
    Terrain
    

    To update your code, you just need to change any string types to match one of the above. For example, if your code had:

    function getBody(): string[] {
      return [ WORK, MOVE, CARRY ];
    }

    Change it to:

    function getBody(): BodyPartConstant[] {  // this line changed
      return [ WORK, MOVE, CARRY ];
    }
  • Some original functions were incorrectly typed to not include null as a possible return. You may need to update your code to reflect this update (ex. findClosestByPath or findClosestByRange)

  • Game.getObjectById() now returns typed objects according to the type of the Id (ex. Id<StructureTower> returns StructureTower type).

    Use of string typed Id, is deprecated and may be removed in the future. When using string Ids, the type of the returned game object is unknown which requires manual type assertion. Previously this function returned any typed objects which could accidently be left untyped;

    If you have code like this (un-type-asserted use of Game.getObjectById)

    interface Memory{
      towerIds: string[];
    }
    
    Memory.towerIds.forEach((towerId) => {
      const tower = Game.getObjectById(towerId); // type of returned tower is 'unknown' instead of 'any'
      tower.attack(targetCreep); // Error Object is of type unknown ts(2571)
    })

    Change it store typed Ids:

    interface Memory{
      towerIds: Array<Id<StructureTower>>;
    }
    
    Memory.towerIds.forEach((towerId) => {
      const tower = Game.getObjectById(towerId); // type of returned tower is StructureTower
      tower.attack(targetCreep);
    })

    If you're already manually asserting the type of the game object, you're not required to change anything immediately however this is deprecated and may be removed in the future.

    const towerId: Id<StructureTower> = ""  as Id<StructureTower>;
    const tower1 = Game.getObjectById(towerId); // recommended use, returns StructureTower type
    const tower2 = Game.getObjectById<StructureTower>(""); // @deprecated returns StructureTower type
    const tower3 = Game.getObjectById("") as StructureTower; // @deprecated returns StructureTower type

    Id<T> types are assignable to string but the reverse is not allowed implicitly. To assign a string type to an Id<T> type, you must explicitly assert the type.

    const typedId: Id<Creep> = "123" as Id<Creep>; // assertion required
    const untypedId1: string = typedId; // no assertion required
  • Game objects have typed id properties id: Id<this>. These typed ids can by passed to Game.getObjectById() to receive typed game objects matching the type of the Id. See above bullet for more details.

    creep.id // has type Id<Creep>
    copy = Game.getObjectById(creep.id) // returns type Creep
    tower.id // has type Id<StructureTower>

Additional (non-breaking) Features:

  • ConstructionSite can be optionally constrained by a structure type (ex. ConstructionSite<STRUCTURE_CONTAINER>). TypeScript will enforce that the type property of the ConstructionSite appropriately matches
  • Resource can optionally be constrained (ex. Resource<RESOURCE_ENERGY>)
  • Mineral can optionally be constrained by MineralConstant (ex. Mineral<RESOURCE_GHODIUM>)
  • Structure can optionally be constrained (ex Structure<STRUCTURE_SPAWN | STRUCTURE_EXTENSION>)
  • Screeps classes derived from Structure (ex StructureContainer) have their type property correspondingly constrained
  • LookAt results are now constrained to the type looked for
  • Results from Find-type functions are now constrained to have a RoomPosition
  • Typings for new RawMemory and RoomVisuals
  • New union type AnyCreep to represent Creep and PowerCreep

Contribute

Issues and Pull Requests are welcome! Please read the Contributing Guidelines and Code of Conduct beforehand.

typed-screeps's People

Contributors

aemino avatar anisoptera avatar arcath avatar bastianh avatar bonzaiferroni avatar bryanbecker avatar chriskitching avatar dependabot[bot] avatar dessix avatar diamondmofeng avatar dmarcuse avatar eldorandev avatar ezolenko avatar jomik avatar jyarbro avatar kotarou avatar lf- avatar madrang avatar markosulamagi avatar mschultheiss83 avatar nhanho avatar pmoehl avatar pyrodogg avatar resir014 avatar seancl avatar sheeo avatar tcdejong avatar thmsndk avatar valerian avatar wtfrank avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

typed-screeps's Issues

Game market changes

Brief Description

Added new method Game.market.getHistory, which contains historical price data for all resources.

Increased per-player market orders limit from 50 to 300.

Added expiration period to market orders. An order expires in 30 days after its creation, and the remaining market fee is returned. Extending the order doesn't update its expiration time.

Game.market.createOrder now accepts parameters in an object notation in order to minimize mistakes caused by wrong order of parameters:

	Game.market.createOrder({
	  type: ORDER_BUY,
	  resourceType: RESOURCE_ENERGY,
	  price: 0.01,
	  totalAmount: 100000,
	  roomName: 'W1N1'
	});

Reference to Screeps Changelog (if available)

Factories, new resources, NPC Strongholds

creep.ticksToLive should be typed as number | undefined

When creep.spawning is true, creep.ticksToLive is undefined. You can see this by evaluating Game.creeps[Game.spawns.Spawn_.spawning.name].ticksToLive for a Spawn_ which is currently spawning a creep. This can result in bugs that should have been caught at compile time, such as creeps spawning in duplicate when filtering for lifespan to determine prespawn.

Your Environment

  • Node.js version: 8.0
  • TypeScript version: 2.6.2
  • typed-screeps version: 2.0.0

Remove deprecated properties and constants

Brief Description

  • Remove FIND_DROPPED_ENERGY constant, which was deprecated long ago. Use FIND_DROPPED_RESOURCES instead.
  • Remove all Structure*.transfer methods which were deprecated long ago. Use Creep.withdraw instead. After closer review it looks like these have previously been removed

Reference to Screeps Changelog (if available)

Factories, new resources, NPC Strongholds

Can't create Record<Id, any>

Expected Behavior

Since Id objects are just strings, I should be able to create a Record using Ids as keys.

Actual Behavior

I get the following error:

Type 'Id<Creep>' does not satisfy the constraint 'string | number | symbol'.
  Type 'Id<Creep>' is not assignable to type 'string'.

Sample code (if available)

var data: Record<Id<Creep>, number> = {};

Your Environment

  • Node.js version: 12.13.0
  • TypeScript version: 3.6.4
  • {typed-screeps or @types/screeps delete as appropriate} version: be96ea9

Game.cpu.halt() missing

Brief Description

Game.cpu.halt() is missing from the type declarations. I'm not entirely sure how type type it, because it interrupts script execution and thus might cause unreachable code as well.

Reference to Screeps Changelog (if available)

https://blog.screeps.com/2018/12/changelog-2018-12-14/ (bottom, under "other changes")
https://docs.screeps.com/api/#Game.halt

Sample code (if available)

Potential usage: force a global reset if we just respawned.

// Check if we just respawned
if (hasRespawned()) {
    // wipe memory
    Memory = { };
    // force global reset
    Game.cpu.halt()
}

Typing:

interface CPU {
    // ... existing entries...
    /**
     * Reset your runtime environment and wipe all data in heap memory.
     */
    halt(): void;
}

As mentioned in the description, I'm not sure if the code interruption can be included in the typings.

Replace uses of any with unknown

unknown offers greater type safety, even without knowing exact type information. Replacing any with unknown - e.g. for return values of Game.getObjectById(id: string) - would help catch errors by requiring type guards, or at least explicit casts. This specific example would work particularly well in conjunction with #92.

Room.getTerrain( ) is missing

I noticed that while the RoomTerrain type is there, the Room type doesn't have the method that generates it. docs.screeps.com/api/#Room.getTerrain

Expected Behavior

getTerrain is suggested and is not marked as incorrect when used

Actual Behavior

getTerrain is not suggested and is marked as incorrect when used

Sample code (if available)

function test (room: Room): void {
    const terrain: RoomTerrain = room.getTerrain();
}

Your Environment

  • Node.js version: v8.12.0
  • TypeScript version: 2.6
  • @types/screeps version: 2.5.1

Unexpected type when trying to get specific structure from 'AnyStructure'

Shouldn't asd2 be of type 123 as well? since AnyStructure has StructureSpawn in its union?

type asd = StructureSpawn['structureType'] extends STRUCTURE_SPAWN ? 123 : never // asd is 123 as expected
type asd2 = AnyStructure['structureType'] extends STRUCTURE_SPAWN ? 123 : never // asd2 is never ??? why

What i'm trying to do is something like Structure<STRUCTURE_SPAWN> and get the type StructureSpawn. If you think of something else to do this behaviour, please let me know c:

Lack of coding style

There seems to be a lack of coding style for the code base here.
Some long lines are broken, some are not.
Some files use 2 space indentation, some use 4.
Thus I had no clue what to do in #88 ๐Ÿ˜‚

Ruins

Brief Description

  • Implement Ruin game object type

When structures are destroyed, they drop a ruin object (similar to tombstones for creeps) which will contain all of the structures resources.

Reference to Screeps Changelog (if available)

Factories, new resources, NPC Strongholds

Cannot redeclare block-scoped variable `Game`

This is related to #26. The current version of typed-screeps declares Game with let instead of var, so extending the interface in other files throws TS2451. To fix it, change line 81 from declare let Game: Game; to declare var Game: Game;.

Your Environment

  • Node.js version: 8
  • TypeScript version: 2.7.2
  • {typed-screeps or @types/screeps delete as appropriate} version: 2.2.2

Factories and Commodities

Brief Description

A new structure is now available at RCL 7: Factory. It allows for creating many new types of resources. Four of these are very special โ€” we have added new raw resources to the game. They have Deposit game object type and can be occasionally found in "highway" rooms. You can harvest them as usual, but they will exhaust over time and have a limited lifespan. Deposits are distributed unevenly across the world map: one resource type per map quadrant (NW, NE, SW, SE).

Reference to Screeps Changelog (if available)

Factories, new resources, NPC Strongholds
PTR Forum Topic
Draft discussion

dist version does not match src version

I've re-discovered the issue with the second declaration of RoomPosition.getDirectionTo returning number instead of DirectionConstant. While this seems to have been fixed in src, the version in dist does not reflect that change.

I was just following the instructions to install using typings, am I meant to compile them myself instead?

How are you supposed to use typed memory?

The new "typed memory" doesn't seem to be working for me.

The CreepMemory is an empty interface, so it lets you set arbitrary data, but reading gets something like

TS2339: Property 'taskMemory' does not exist on type 'CreepMemory'.

The README implies you can just define an interface also called CreepMemory but that does nothing.

how are you actually supposed to use this?

Weird issue using FIND_MY_STRUCTURES and STRUCTURE_WALL

Expected Behavior

I want to write something like the following and have it compile:

tower.room.find(FIND_MY_STRUCTURES, {
    filter: (st) => st.structureType === STRUCTURE_WALL,
});

Actual Behavior

// Works fine...
tower.room.find(FIND_STRUCTURES, {
    filter: (st) => st.structureType === STRUCTURE_WALL,
});

// Also works fine...
tower.room.find(FIND_MY_STRUCTURES, {
    filter: (st) => st.structureType === STRUCTURE_RAMPART,
});

// Doesn't compile!
// Error: ~/screeps-typescript-starter/src/main.ts(16,23): semantic error TS2365 Operator '==='
// cannot be applied to types '"extension" | "rampart" | "spawn" | "link" | "storage" | "tower"
// | "observer" | "powerSpawn" | "e...' and '"constructedWall"'.
tower.room.find(FIND_MY_STRUCTURES, {
    filter: (st) => st.structureType === STRUCTURE_WALL,
});`

It seems very strange that this doesn't compile, when other very similar code does. So I think this must be a bug? To make sure the problem wasn't with my own project, I cloned screeps-typescript-starter and was able to reproduce the problem again.

Your Environment

  • Node.js version: v8.11.3

Basically a newly cloned screeps-typescript-starter:

"devDependencies": {
    "@types/lodash": "^3.10.1",
    "@types/node": "^10.5.5",
    "@types/screeps": "^2.4.0",
    "prettier": "^1.14.0",
    "rollup": "^0.63.4",
    "rollup-plugin-clear": "^2.0.7",
    "rollup-plugin-commonjs": "^9.1.4",
    "rollup-plugin-node-resolve": "^3.3.0",
    "rollup-plugin-screeps": "^0.1.2",
    "rollup-plugin-typescript2": "^0.16.1",
    "tslint": "^5.9.1",
    "tslint-config-prettier": "^1.14.0",
    "typescript": "^2.9.2"
  },
  "dependencies": {
    "source-map": "~0.6.1"
  }

StoreDefinition updates

Brief Description

  • Update StoreDefinition type to include new Store functionality
  • Deprecate old properties (e.g. carry, energy, energyCapacity)

Reference to Screeps Changelog (if available)

Factories, new resources, NPC Strongholds

POSSIBLY BREAKING CHANGE: Implemented new global Store prototype. All structures and creeps now use this prototype as their store property. Old style properties are now considered deprecated. See documentation for more details, and also this previous discussion.

If you have any troubles because of this change, it most likely falls into one of these categories:

You're checking for structure.store presence to distinguish storages and containers from spawns and extensions. Use structure.structureType check instead, or structure.store.getCapacity(RESOURCE_ENERGY) !== null.

You're comparing .store[resource] === undefined. Now all absent resources are equal to 0.

You're trying to redefine store property, which is now non-configurable.

Feature: Add types for Power Creeps release

Expected Behavior

Power Creeps are currently available on PTR and are expected to be released on MMO on March 18th. Types for the Power Creeps entities should be added or updated.

  • Game.gpl - ptr
    • New
  • Game.powerCreeps - ptr
    • New
  • Game.spawns - ptr
    • May contain StructureSpawn and StructurePowerSpawn entities?
    • PowerSpawns are not available in Game.spawns and there is no corresponding Game.powerSpawns.
  • InterShardMemory - ptr
    • Also expected to launch with Power Creeps
  • Memory.powerCreeps - ptr
    • New
  • PowerCreep - ptr
    • New
  • StructurePowerSpawn - ptr
    • Exists but createPowerCreep should be removed

Tombstone support is missing.

LOOK_TOMBSTONE and other type definitions for tombstones are missing despite being in the game.

Expected Behavior

Tombstone api changes should be in the latest version.

Actual Behavior

Tombstone api changes are not in the latest version.

Sample code (if available)

        let tombstone = creep.room.lookForAtArea(LOOK_TOMBSTONE, creep.pos.y - 2, creep.pos.x - 2, creep.pos.y + 2, creep.pos.x + 2, true);

Your Environment

  • Node.js version: v8.10.0
  • TypeScript version: Version 2.7.2
  • {@types/screeps} version: 2.2.0

Transaction missing optional `order`

As defined http://docs.screeps.com/api/#Game-market

It mentions an optional order property, I suggest the following changes:

interface TransactionOrder {
  id: string,
  type: string,
  price: number,
}

and modifying Transaction as follows

interface Transaction {
    transactionId: string;
    time: number;
    sender?: {
        username: string;
    };
    recipient?: {
        username: string;
    };
    resourceType: ResourceConstant;
    amount: number;
    from: string;
    to: string;
    description: string;
    order?: TransactionOrder;
}

store property not in Structure

Expected Behavior

I think the store property should be an optional field for a structure, as it is implemented by StructureContainer, and returned by calling a FIND_STRUCTURES. Now I am a bit new to typescript, so not completely sure what the desired behaviour should be

Sample code

let target = creep.pos.findClosestByRange(FIND_STRUCTURES, {
            filter: (structure: Structure) => {
                return (structure.structureType == STRUCTURE_CONTAINER) 
                      && structure.store ? structure.store.energy < structure.storeCapacity : false;
            }
        });

The only way to get the above working for me is to put an any type in the function call: structure: Structure

Your Environment

  • Node.js version: 8.9.3
  • TypeScript version: 2.6.2

Add TERMINAL_COOLDOWN

The TERMINAL_COOLDOWN does not appear to be in the typings.

Expected Behavior

TERMINAL_COOLDOWN defined

Actual Behavior

TERMINAL_COOLDOWN undefined

Sample code (if available)

declare const TERMINAL_COOLDOWN: number;

Your Environment

  • Node.js version: 8.10.0
  • TypeScript version: 2.7.1
  • @types/screeps version: 2.2.1

`getObjectById` and `object.id` interfaces are untyped

Currently all Screeps id attributes are implemented as string, not Id<Object>.

Expected Behavior

It should be Id<RoomObject> or similar type argument, so that they can be saved, and then restored:
getObjectById(id<RoomObject>) ->ย RoomObject?
Main point of using object ids is saving them to memory to keep a hang of any particular object for the future.

Actual Behavior

Currently all Screeps id attributes are string. Some objects do not have this property at all.

Your Environment

  • @types/screeps version: 2.4.1 commit: ed699e3

withdraw not working with tombstones

Guess withdraw should look like this now?

withdraw(target: Structure | Tombstone, resourceType: ResourceConstant, amount?: number): ScreepsReturnCode

Two errors with `StructureLab` typings

There are two errors with the typings for StructureLab.

  1. If a lab is empty, lab.mineralType == null. Currently, mineralType is typed as MineralConstant; should be MineralConstant | null or MineralConstant | undefined (the former is technically what Screeps says for an empty lab, but the latter is better practice for TS)

  2. Lab mineral types should actually be typed as _ResourceConstantSansEnergy | undefined, since they can contain more than just tier 1 resources.

findClosestByRange(FIND_MY_STRUCTURES filter does not allow STRUCTURE_CONTAINER

It would appear that STRUCTURE_CONTAINER is not considered a owned structure type

Expected Behavior

using creep.pos.findClosestByRange(FIND_MY_STRUCTURES allows for the structure.structureType to be of the type STRUCTURE_CONTAINER

Actual Behavior

using creep.pos.findClosestByRange(FIND_MY_STRUCTURES does not allow for the structure.structureType to be of the type STRUCTURE_CONTAINER

TypeScript complains about AnyOwnedStructure not containing StructureContainer making the sample code invalid

Sample code (if available)

const target = creep.pos.findClosestByRange(FIND_MY_STRUCTURES, {
        filter: structure => {
          switch (structure.structureType) {
            case STRUCTURE_CONTAINER: // the compiler throws an error about this line
              const container = structure as StructureContainer
              return _.sum(container.store) < container.storeCapacity && haulers.length > 0
          }

          return false
        }
      })

Adding this to index.d.ts makes the compiler happy

type AnyOwnedStructure =
  | StructureContainer
...

Your Environment

  • Node.js version: 12.3.1
  • TypeScript version: 2.9.2
  • @types/screeps version: 2.5.4

LookAtTypes needs a non optional counterpart

interface AllLookAtTypes {
    constructionSite: ConstructionSite;
    creep: Creep;
    energy: Resource<RESOURCE_ENERGY>;
    exit: any;  // TODO what type is this?
    flag: Flag;
    mineral: Mineral;
    nuke: Nuke;
    resource: Resource;
    source: Source;
    structure: Structure;
    terrain: Terrain;
}

type LookAtTypes = Partial<AllLookAtTypes>;
interface RoomPosition {
    lookFor<T extends keyof AllLookAtTypes>(type: T): Array<AllLookAtTypes[T]>;
}

interface Room {
    lookForAt<T extends keyof AllLookAtTypes>(type: T, x: number, y: number): Array<AllLookAtTypes[T]>;
    lookForAt<T extends keyof AllLookAtTypes>(type: T, target: RoomPosition | _HasRoomPosition): Array<AllLookAtTypes[T]>;
}

This fixes RoomPosition.lookFor(LOOK_CREEPS) returning Array<Creep | undefined> instead of Creep[]

findPathOpts incomplete (missing plainCost and swampCost)

Expected Behavior

Type FindPathOpts should recognize plainCost and swampCost.

Actual Behavior

Linter errors: properties are undefined in FindPathOpts

Sample code (if available)

    const myOpts: FindPathOpts = { range: 1 };
    myOpts.plainCost = 1;
    myOpts.swampCost = 1;```

```Linter:
=> Property 'plainCost' does not exist on type 'FindPathOpts'.
=> Property 'swampCost' does not exist on type 'FindPathOpts'```


### Your Environment

- Node.js version: 8.9.4
- TypeScript version: 3.1.3
- `@types/screeps` version: 2.5.1

Missing safemode constants

Expected Behavior

Global constant SAFE_MODE_DURATION being present in index.d.ts

Actual Behavior

Cannot find name 'SAFE_MODE_DURATION'.

Sample code (if available)

// check for controller, progress and safe mode
    const room = Game.rooms[rNames[0]];
    if (!room.controller || !room.controller.my || room.controller.level !== 1 || room.controller.progress ||
       !room.controller.safeMode || room.controller.safeMode !== SAFE_MODE_DURATION - 1) {
        return false;
    }

Your Environment

  • Node.js version: 8.9.4
  • TypeScript version: 2.5
  • @types/screeps version: 2.4.1

Best type for Game object Index Signatures?

I've been using typed-screeps for a few months now, and have been getting more familiar with TypeScript. This library is extremely useful and it's been great. There's still one thing that seems odd to me, and I'm wondering if it's an opportunity for a PR.

When you do a index into one of the Game objects, the result is always non-nullable, even though the result actually may be undefined. For example:

let nonExistentFlagName = "nonExistentFlagName";

// "Game.flags" has type "{ [flagName: string]: Flag }"

let flag1 = Game.flags[nonExistentFlagName];

// "flag1" has type "Flag" but value "undefined"

The type of Game.flags certainly looks reasonable, and seems like idiomatic TypeScript. But flag1 is always a Flag even when the lookup has failed and the value is undefined. So it seems that flag1 should really have type Flag | undefined. And following that logic, Game.flags should really have type { [flagName: string]: Flag | undefined }.

My understanding is that, by default, all types in TypeScript are nullable. So this really only matters when strict mode is turned on. But I still think it would be nice to have the option for the extra type safety, and it seems more correct. Plus, screeps-typescript-starter comes with strict mode turned on.

The other thing I might mention, is that ES6 Map.get returns a nullable type. For example:

// Imagining that "Game.flags" had type "Map<string, Flag>"...

let flag1 = Game.flags.get(nonExistentFlagName);

// "flag1" has type "Flag | undefined"

So there is some precedence I think. Anyway, like I mentioned before, the change could be accomplished by adding | undefined to the various Game objects. I don't think the change would require too much work for users. In some cases it might uncover bugs. In other cases, users would just have to add ! non-null assertion operators. For example:

let existentFlagName = "existentFlagName";

let flag1 = Game.flags[existentFlagName]!;

// "flag1" forced to type "Flag"

At the end of the day, it would still require some user intervention, and it would break existing code. So it is a big change.

So did all of that make sense? Does a change like what I'm proposing make sense? (Probably with a version bump.) If so, I would be happy to write a PR. Please let me know.

Push 3.0 Update to DT

Things are finally settling down enough that I'm planning to push the 3.0 update to Definitely Typed Saturday November 23rd.

Update checklist

If you are just submitting a PR, this isn't needed, but for new maintainers, when preparing a new version or updates:

  1. Update the changelog with links to each relevant PR
  2. Update the contributors list.
  3. Update version numbers if required
  4. (If releasing) Package a release / Update the relevant draft release
  5. Close / Update relevant issues
  6. (If publishing) Submit a PR to Definitely-Typed

TypeScript arguments trouble

const receivers = creep.room.find(FIND_MY_SPAWNS);
        const receiver = receivers[0];
        if (creep.transfer(receiver, RESOURCES_ALL) === ERR_NOT_IN_RANGE) {
          creep.moveTo(receiver);
        }

Result - error:

(18,27): Argument of type 'RoomPosition | _HasRoomPosition' is not assignable to parameter of type 'Source | Mineral'.
Type 'RoomPosition' is not assignable to type 'Source | Mineral'.
Type 'RoomPosition' is not assignable to type 'Mineral'.
Property 'density' is missing in type 'RoomPosition'.

Seems like it is related with room.ts:81
find<T extends _HasRoomPosition | RoomPosition>(type: FindConstant, opts?: { filter: Object | Function | string }): T[];

Add namespace

All global objects in a library declaration like this should be in their own namespace.

This would involve wrapping the contents of every file in declare namespace creeps {...} and then (probably) removing every other declare.

Missing ERR_NOT_ENOUGH_RESOURCES in Creep interface on build action

Expected Behavior

Creep.build is supposed to return a ERR_NOT_ENOUGH_RESOURCES in the interface on the build action; as noted in the comment of the function and the documention of Screeps.

type CreepActionReturnCode =
OK |
ERR_NOT_OWNER |
ERR_BUSY |
ERR_INVALID_TARGET |
ERR_NOT_IN_RANGE |
ERR_NO_BODYPART |
ERR_TIRED;

typed-screeps/src/creep.ts

Lines 100 to 102 in 7aba304

* @returns Result Code: OK, ERR_NOT_OWNER, ERR_BUSY, ERR_NOT_ENOUGH_RESOURCES, ERR_INVALID_TARGET, ERR_NOT_IN_RANGE, ERR_NO_BODYPART, ERR_RCL_NOT_ENOUGH
*/
build(target: ConstructionSite): CreepActionReturnCode | ERR_RCL_NOT_ENOUGH;

Actual Behavior

Creep.build does not support ERR_NOT_ENOUGH_RESOURCES in the interface;

Sample code (if available)

function BuilderBuild(creep: Creep) {
    const targets = creep.room.find(FIND_CONSTRUCTION_SITES);
    if (targets.length > 0) {
        const target = targets[0];
        switch (creep.build(target)) {
            case ERR_NOT_IN_RANGE:
                creep.moveTo(target);
                break;
            case ERR_NOT_ENOUGH_RESOURCES:
                creep.building.upgrading = false;
                return;
            case OK:
                break;
            default:
                console.log("BuilderBuild, got error: ", creep.build(target));
            // unknown
        }
    }
}

Your Environment

  • Node.js version: v8.10.0
  • TypeScript version: 2.8.1
  • @types/screeps version: 2.2.1

Deprecations for StructureSpawn [2017-11-06]

Leaving this here so I remember to do it later:

Deprecated

  • spawn.canCreateCreep(body, [name])
  • spawn.createCreep(body, [name], [memory])
  • spawn.transferEnergy(target, [amount])

A deprecation notice should be added to the docblocks.

typed-screeps 2.0 does not allow for modification of the `Game` interface

I do a lot of per-tick caching on a Game.cache object. Modifying the Game interface results in the error TS2451: Cannot redeclare block-scoped variable 'Game'.:

image

However, if I change line 981 of the screeps.d.ts file of typed-screeps from declare const Game: Game; to declare var Game: Game;, this goes away. It seems as though the typings doesn't allow you to directly modify the Game object by declaring it as a constant rather than a var.

Expected Behavior

Using interface Game { ... } in a separate declaration file should produce no issue, such as using interface Creep { ... }.

Actual Behavior

Compiler sees Game as declared as a constant and gets mad if you try to modify the interface.

Sample code (if available)

My declaration file:

interface Game {
	cache: {
		assignments: { [ref: string]: { [roleName: string]: string[] } };
		targets: { [ref: string]: string[] };
		objectives: { [ref: string]: string[] };
		structures: { [roomName: string]: { [structureType: string]: Structure[] } };
		drops: { [roomName: string]: { [resourceType: string]: Resource[] } };
		constructionSites: { [roomName: string]: ConstructionSite[] };
	};
	icreeps: { [name: string]: ICreep };
	directives: { [name: string]: IDirective };
}

Screeps typings:

interface Game {
    ...
}
declare const Game: Game;

Your Environment

  • Node.js version: 8
  • TypeScript version: 2.6.1

Room.getTerrain() seems to be missing

Expected Behavior

Room.getTerrain() returning a Room.Terrain object

Actual Behavior

Property 'getTerrain' does not exist on type 'Room'

Sample code (if available)

  const thisRoom = Game.spawns.Spawn1.room;
  const terrain = thisRoom.getTerrain();

Your Environment

  • Node.js version: V8 / 6.1.534.50 (I hope that's the right one)
  • TypeScript version: 3.1.1
  • @types/screeps version: 2.5.1

Indexing via Type

When I try to build a project I get several compilation errors. It looks like it's trying to use the constant associated with the Type?... but I'm not really sure. Typings are mysterious in general to me, and this particular declaration file is like the blackest magic I've ever seen. Any thoughts?

This happens even in an empty project if I have the package referenced as a Dependency.

It looks like this may be a duplicate, but I'm not positive, so I'm posting to be on the safe side.

Expected Behavior

Error free compilation

Actual Behavior

Compile-time error
Build: Type 'T' cannot be used to index type 'FindTypes'.

Sample code (if available)

[1547] type FilterFunction<T extends FindConstant> = (object: FindTypes[T]) => boolean;
[2428] findClosestByPath<K extends FindConstant>(type: K, opts?: FindPathOpts & { filter?: FilterFunction<K>, algorithm?: string }): FindTypes[K];
[2425] findClosestByRange<K extends FindConstant>(type: K, opts?: {filter: FilterFunction<K>}): FindTypes[K];
[2459] findInRange<K extends FindConstant>(type: K, range: number, opts?: {filter: any| string}): Array<FindTypes[K]>;
[2864] find<K extends FindConstant>(type: K, opts?: FilterOptions<K>): Array<FindTypes[K]>;

Your Environment

  • Building via Visual Studio Community 2017
  • Node.js version: Unsure
  • TypeScript version: 2.6.1
  • @types/screeps version: 2.1.0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.