这是这question.人的后续行动
我想实现的目标是: 将多个子类传递给一个函数,有没有办法返回一个以"模式"形式传递的子类类型的对象?这样我就可以保留所有的智能感知功能.
低于我失败的try .
class Component {
get name(): string {
return this.constructor.name
}
}
class Direction extends Component {
x: number
y: number
constructor(x: number = 0, y: number = 0) {
super()
this.x = x
this.y = y
}
}
class Rectangle extends Component {
x: number
y: number
w: number
h: number
constructor(x: number, y: number, w: number, h: number) {
super()
this.x = x
this.y = y
this.w = w
this.h = h
}
}
class Entity {
components: Map<string, Component>
constructor(...components: Component[]) {
this.components = new Map()
components.forEach(component => this.add(component))
}
get<C extends Component[]> (...components: { [P in keyof C]: new (...args: any[]) => C[P] }): Record<string, Component> {
return components.reduce(
(accumulator, component) => {
accumulator[component.name.toLocaleLowerCase()] =
this.components.get(component.name)!
return accumulator
},
{} as Record<string, Component>
)
}
add(component: Component) {
this.components.set(component.name, component)
}
}
const player = new Entity(
new Rectangle(100, 100, 100, 100),
new Direction(1, 1)
)
const p_components = player.get(Rectangle, Direction)
console.log(p_components.rectangle)
// Intellisense doens't know p_components properties
// Intellisense infers p_components.rectangle as Components - It should be Rectangle instead
我也在网上搜索过,我找到的最接近这个数字的是this.但我不知道如何在我的代码中实现它,以及它是否有帮助.