属性在类型上不存在,当它明显存在时

问题描述

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

假设我有一个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,而不是实现/扩展 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...