【发布时间】:2020-08-03 19:20:22
【问题描述】:
我正在编写一个存储联合类型的自定义集合类。现在我想要一个访问器方法,它返回一个正确(单一)类型的项目。这是我想出的:
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)
如您所见,当消费代码提供了错误的类型时,它会收到undefined 值。有什么方法可以让这段代码更安全?
我知道我可能需要运行时检查,但我想避免在每次调用 get 之后都必须调用 instanceof。
另一种选择是为每种类型添加 get 方法,但这会违反开闭原则,因为对于每种新类型,我还必须添加一个 getter。
有没有更好的办法?
【问题讨论】:
-
您是否考虑过实现自己的类型保护?见:typescriptlang.org/docs/handbook/…
-
像
get<T extends AllGames>(idx: number): Tcannot possibly be implemented correctly这样的签名。
标签: typescript generics collections