gpt4 book ai didi

javascript - Typescript - 扩展接口(interface)(无构造函数)的类(带构造函数)

转载 作者:行者123 更新时间:2023-11-28 16:44:36 25 4
gpt4 key购买 nike

我的界面如下所示:

interface Person {
id: number
name: string
}

我有一个实现此接口(interface)的类:

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')

我做错了什么/遗漏了什么?

最佳答案

尝试

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) { }
}

关于javascript - Typescript - 扩展接口(interface)(无构造函数)的类(带构造函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60696983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com