我已声明接口(interface)如下
interface Base {
required: string;
}
我已经在类中实现了接口(interface),例如
class MyClass implements Base{
method(): void {
console.log(this.required);
}
}
但是我收到以下错误
severity: 'Error' message: 'Class 'MyClass' incorrectly implements interface 'Base'. Property 'required' is missing in type 'MyClass'.' at: '5,7' source: 'ts'
severity: 'Error' message: 'Property 'required' does not exist on type 'MyClass'.' at: '7,26' source: 'ts'
如果我在类里面再次声明 required: string;
则不会出现错误
interface Base {
required: string;
}
class MyClass implements Base{
required: string;
method(): void {
this.required="ddd";
console.log(this.required);
// you can access HTMLElement
}
}
var ss=new MyClass();
ss.method();
最佳答案
如果您不想删除 requried: string
两次,请使用 class
instate interface
作为 Base
并扩展状态实现。
class Base {
required: string;
}
class MyClass extends Base{
method(): void {
this.required="ddd";
console.log(this.required);
// you can access HTMLElement
}
}
查看playground .
关于javascript - Typescript 实现接口(interface)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42173134/