我正在使用 Typescript 编写代码,并且正在尝试访问任何实现名为 ObjectTemplate 的接口的对象上名为 id 的属性。
假设我有一个 class Player
,它 implements ObjectTemplate
,它有一个 id 属性。然后,我传入new Player()
下面addObject()
提供的函数。
当我尝试访问new Player().id
(或我在参数中命名的obj.id
)时,我收到一条错误消息,告诉我Property 'id' does not exist on type 'ObjectTemplate'
interface ObjectTemplate {
id: string
}
class Player implements ObjectTemplate {
id: string
name: string
constructor(name: string) {
this.name = name
}
}
class Entity implements ObjectTemplate {
id: string
health: number
constructor(health: number) {
this.health = health
}
}
const createId = () => 'randomId'
class ObjectList<ObjectTemplate> {
objects: { [key: string]: ObjectTemplate }
constructor() {
this.objects = {}
}
addObject(obj: ObjectTemplate) {
const newId = createId()
obj.id = newId // I get an error here.
this.objects[newId] = obj
}
}
const playerList: ObjectList<Player> = new ObjectList()
playerList.addObject(new Player("someName"))
const entityList: ObjectList<Entity> = new ObjectList()
entityList.addObject(new Entity(100))