typed-screeps icon indicating copy to clipboard operation
typed-screeps copied to clipboard

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

Open categoricalcat opened this issue 6 years ago • 3 comments

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:

categoricalcat avatar Oct 28 '19 12:10 categoricalcat

Could you provide a more inclusive example of what you're trying to do?

AnyStructure['structureType'] doesn't extend STRUCTURE_SPAWN because it could also be any other structure type string literal.

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

pyrodogg avatar Oct 28 '19 17:10 pyrodogg

Could you provide a more inclusive example of what you're trying to do?

AnyStructure['structureType'] doesn't extend STRUCTURE_SPAWN because it could also be any other structure type string literal.

Basically, i have a findStructure function and i want it to return the structure class Right now, my current temporary solution is doing like

type Structures = {
  [STRUCTURE_CONTAINER]: StructureContainer
  [STRUCTURE_CONTROLLER]: StructureController
  [STRUCTURE_EXTENSION]: StructureExtension
  // ... all the other structures
}

// this will be of type 'StructureContainer'
let container: Structures[STRUCTURE_CONTAINER] = findClosestStructure(creep, STRUCTURE_CONTAINER)

categoricalcat avatar Oct 29 '19 12:10 categoricalcat

Using this kind of LookupTypes is perfectly fine, in fact typed-screeps uses them as well.

All you have to do is setting up your Structures LookupType and define your function like so:

function findStructure<T extends keyof Structures>(type: T): Structures[T]

and your return type will change depending on your parameter:

const container = findStructure(STRUCTURE_CONTAINER);
const controller = findStructure(STRUCTURE_CONTROLLER);

RiftLurker avatar Oct 29 '19 14:10 RiftLurker