1

I'm writing a custom collection class that stores a union type. Now I want to have an accessor method that returns a correctly (single)-typed item. This is what I came up with:

class GameA {
    constructor(public name: string) {}
}

class GameB {
    constructor(public numberOfTries: number) {}
}

type AllGames = GameA | GameB;

class GameCollection {
    store: Array<AllGames>;
    constructor() {
        this.store = [];
    }
    add(g: AllGames) {
        this.store.push(g)
    }
    get<T extends AllGames>(idx: number): T {
        const item = this.store[idx];
        if (typeof item === 'undefined') {
            throw new Error("Index out of bounds");
        }
        // Any way to check at runtime that item is of type T?
        return item as T;
    }
}

const store = new GameCollection()
store.add(new GameA('Anton'))
store.add(new GameB(42))

console.log('First item (has name):', store.get<GameA>(0).name)
console.log('Second item (name is undefined):', store.get<GameA>(1).name)

As you can see, when consuming code provides the wrong type, it will received undefined values. Is there any way to make this code more type safe?

I know that I'll probably need a runtime check, but I want to avoid having to call instanceof after every call to get.

Another option would be to add get methods for each type, but that would violate the open-closed principle because with every new type I'd also have to add a getter.

Is there any better way?

2

2 Answers 2

1

The closest I can think of is using discriminated unions, and changing the get function to actually take in a type. Providing the type as a generic instead will have no effect at runtime.

// Making it so there's a `type` field that can be discriminated on at runtime 
class GameA {
  constructor(name: string) {
    this.name = name
  }
  name: string
  type: 'GameA' = 'GameA'
}

class GameB {
  constructor(numberOfTries: number) {
    this.numberOfTries = numberOfTries
  }
  numberOfTries: number
  type: 'GameB' = 'GameB'
  name: undefined
}

type AllGames = GameA | GameB

class GameCollection {
  store: AllGames[]
  constructor() {
    this.store = []
  }
  add(g: AllGames) {
    this.store.push(g)
  }
  get(idx: number, type: AllGames['type']) { // updating so it takes a type argument that's available at runtime
    const item = this.store[idx]
    if (!item) {
      throw new Error('Index out of bounds')
    }

    if (item.type === type) {
      return item
    }
    throw new Error('No Game of type ' + type + ' at index ' + idx)
  }
}

const store = new GameCollection()
store.add(new GameA('Anton'))
store.add(new GameB(42))

console.log('First item (has name):', store.get(0, 'GameA').name) // name is correctly typed to undefined | string 
console.log('Second item (name is undefined):', store.get(1, 'GameA').name) // name is correctly typed to undefined | string 

1

As you alluded to, you will need a runtime check. TypeScript's static type system is erased when compiled to JavaScript, so the lines store.get<GameA>(0) and store.get<GameB>(0) both compile to store.get(0). This implies that there is no possible way for them to behave differently from each other.

Instead, you could change your get() method so it takes some type information as an actual runtime parameter instead of as only a type parameter. The most straightforward thing to pass in is the constructor of the class instance you're trying to get:

get<T extends AllGames>(ctor: new (...args: any) => T, idx: number): T {
    const item = this.store[idx];
    if (typeof item === 'undefined') {
        throw new Error("Index out of bounds");
    }
    if (!(item instanceof ctor)) {
        throw new Error("Item is the wrong type");
    }
    return item;
}

The call isn't very different from before:

console.log('First item:', store.get(GameA, 0).name); // Anton
console.log('Second item:', store.get(GameA, 1).name); // runtime error

but now you'll get a runtime error as soon as you try to get() something of the wrong type. I'm not sure if this is what you're looking for exactly, though.


Perhaps you'd like the compiler to give an error when you get() something of the wrong type, or even better, have the compiler know what the type will be when you call get(). Meaning that when you call store.add(new GameA('Anton')), the compiler will modify the type of store to remember that its argument at index 0 is a GameA and not a GameB. This is possible with assertion functions, although they're somewhat painful to use:

type Next = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
class GameCollection<N extends number = 0, A extends Record<number, AllGames> = {}> {
    store: Array<AllGames> & A;
    constructor() {
        this.store = [] as any;
    }
    add<T extends AllGames>(g: T): asserts this is GameCollection<Next[N], A & Record<N, T>> {
        this.store.push(g)
    }
    get<N extends keyof A>(idx: N): A[N] {
        return this.store[idx];
    }
}

Here we've removed all runtime checking and instead, have add() narrow the type of store. I've had to put together Next so the compiler can understand that each add() stores a value at the next index; there's probably a better way to do that but this is just a sketch.

So here's how we'd use it. The most painful part of assertion functions is that you have to add explicit annotations in places you didn't have to before:

const store: GameCollection = new GameCollection()
// ------> !!!!!!!!!!!!!!!!
// this annotation is NECESSARY;

If you inspect store, it's type is:

// const store: GameCollection<0, {}>

Then watch what happens after each add():

store.add(new GameA('Anton'));
store; // const store: GameCollection<1, Record<0, GameA>>
store.add(new GameB(42));
store; // const store: GameCollection<2, Record<0, GameA> & Record<1, GameB>>

So now, store can be used like this:

console.log('First item:', store.get(0).name); // okay
console.log('Second item:', store.get(1).name); // error!
// ------------------------------------> ~~~~
// no name on GameB
store.get(2); // error! 
// -----> ~
// 2 is not assignable to 0 | 1

I think this is neat, but it's probably not a great idea in general unless you plan to both create and use these collections inside related pieces of TypeScript code. If someone hands you some unknown GameCollection then the compiler doesn't know anything about its contents, and you're stuck doing runtime checks again.


Anyway, hope that helps; good luck!

Playground link to code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.