1

我正在使用 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))

操场

4

1 回答 1

2

我认为您的模板语法是错误的。您使用名为 ObjectTemplate 的新类型声明 ObjectList,而不是实现/扩展 ObjectTemplate 的类型。

interface ObjectTemplate {
    id: string
}

class Player implements ObjectTemplate {
    id: string
    name: string
    
    constructor(name: string) {
        this.id = '0';
        this.name = name
    }
}

class Entity implements ObjectTemplate {
    id: string
    health: number
    
    constructor(health: number) {
        this.id = '0';
        this.health = health
    }
}

const createId = () => 'randomId'


class ObjectList<T extends ObjectTemplate> {
    objects: { [key: string]: T }

    constructor() {
        this.objects = {}
    }

    addObject(obj: T) {
        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))

我不知道打字稿,但这是我从阅读文档中得到的: https ://www.typescriptlang.org/docs/handbook/generics.html

于 2021-03-18T23:31:39.020 回答