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
get<T extends AllGames>(idx: number): T
cannot possibly be implemented correctly.