属性 在类型上不存在,但显然存在

Property does not exist on type, when it clearly does

我正在用 Typescript 编写代码,我正在尝试访问任何实现名为 ObjectTemplate 接口的对象上的 属性 命名 id。

假设我有一个 class Player,它实现了 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))

Playground

我认为您的模板语法有误。您正在使用名为 ObjectTemplate 的新类型声明 ObjectList,而不是 implements/extends 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