我还很擅长使用Typescript,并且无法绕过接口。据我所知,接口是类的描述或类的合同。它允许我定义一个类可以具有哪些属性以及它们是哪种类型。我尝试实现它,但总是得到这个错误:
error TS2420: Class 'ResultPage' incorrectly implements interface 'ResultPageInterface'.
Property 'entries' is missing in type 'ResultPage'.
以下是界面的代码
export interface ResultPageInterface {
entries:Array<any>;
page_number:number;
page_size:number;
total_entries:number;
}
export class ResultPage implements ResultPageInterface {}
这里是我想要使用它的课程。
import { Injectable } from '@angular/core';
import { ResultPage } from '../interfaces/result-page.interface';
@Injectable()
export class SomeClass {
constructor() {}
buildPage(res:any): ResultPage {
let page:ResultPage = new ResultPage();
page.entries = res.data;
page.page_number = res.pagination.page_number;
page.page_size = res.pagination.page_size;
page.total_entries = res.pagination.total_entries;
return page;
}
}
答案 0 :(得分:4)
您还需要将成员放在类中,以便它确实实现接口:
class ResultPage implements ResultPageInterface {
public entries: Array<any>;
public page_number: number;
public page_size: number;
public total_entries: number;
constructor() {
this.entries = [];
}
}
您也可以将成员设为私有并使用getter:
class ResultPage implements ResultPageInterface {
private _entries: Array<any>;
private _page_number: number;
private _page_size: number;
private _total_entries: number;
constructor() {
this._entries = [];
}
public get entries() {
return this._entries;
}
public get page_number() {
return this._page_number;
}
public get page_size() {
return this._page_size;
}
public get total_entries() {
return this._total_entries;
}
}
答案 1 :(得分:3)
implements ResultPageInterface
您声明ResultPage
实施ResultPageInterface
但实际上没有。{/ p>
应该是
export class ResultPage implements ResultPageInterface {
entries:Array<any>;
page_number:number;
page_size:number;
total_entries:number;
}
答案 2 :(得分:0)
以防万一您犯了愚蠢的错误。我今天遇到了同样的错误。
src / app / components / home / home.component.ts(11,3)中的ERROR:错误 TS2322:类型'undefined []'无法分配给类型'StreamData'。
类型'undefined []'中缺少属性'messageId'。 src / app / components / home / home.component.ts(18,24):错误TS2339: 类型“ StreamData”不存在属性“ push”。
我将代码从dashboardData: StreamData = [];
更改为dashboardData: StreamData[] = [];
,从而解决了该问题。