【问题标题】:Typescript - Class (with constructor) that extends an interface (no constructor)Typescript - 扩展接口(无构造函数)的类(带构造函数)
【发布时间】:2020-03-16 06:07:20
【问题描述】:

我的界面看起来像:

interface Person {
  id: number
  name: string
}

我有一个实现这个接口的类:

class PersonClass implements Person {
  id: number = 123
  name: string = 'Kevin'
}

上面的工作正常,但是是硬编码的。相反,我希望在创建类时初始化这些值。例如:

class PersonClass implements Person {
  constructor(id, name) {
    this.id = id,
    this.name = name
  }
  id = this.id       // ERROR: Property 'id' is used before its initialization.
  name = this.name   // ERROR: Property 'name' is used before its initialization.
}

如上所示,我在尝试使用构造函数时遇到错误。

我想要从这一切中创建新的 PersonClass 实例并在那时初始化它的值:

// Should be successful
new PersonClass(1, 'Sandra')  

// Should trigger an error
new PersonClass('McDonalds', 'Fries')

我做错了什么/错过了什么?

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    试试

    class PersonClass implements Person {
        id: number;
        name: string;
        constructor(id: number, name: string) {
            this.id = id;
            this.name = name;
        }
    }
    

    甚至:

    class PersonClass implements Person {
        constructor(public id: number, public name: string) { }
    }
    

    【讨论】:

    • 你是个传奇。这行得通。但是,我仍然能够创建一个new PersonClass 实例并使用string 而不是number 初始化id。我不应该得到一个错误吗?
    • 你能检查一下你有没有上面的最新版本(刷新页面!)?他们都为我工作。我编辑了几次答案,试图准确地解决这个问题。我的第一个剪辑没有定义足够的类型。
    • 请在底部的原始问题中查看我的编辑。
    • 我从 .js 文件而不是 .ts 文件实例化 PersonClass (new PersonClass)。感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2019-01-07
    • 2012-01-09
    相关资源
    最近更新 更多