打字稿/角度2:属性缺少类型

前端之家收集整理的这篇文章主要介绍了打字稿/角度2:属性缺少类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对Typescript仍然很陌生,并且难以绕过接口.据我所知,接口是类的描述或类的合同.它允许我定义一个类可以具有哪些属性以及它们是哪种类型.我尝试实现它,但总是得到这个错误
error TS2420: Class 'ResultPage' incorrectly implements interface 'ResultPageInterface'.
Property 'entries' is missing in type 'ResultPage'.@H_404_2@ 
 

这是界面的代码

export interface ResultPageInterface {
  entries:Array<any>;
  page_number:number;
  page_size:number;
  total_entries:number;
}

export class ResultPage implements ResultPageInterface {}@H_404_2@ 
 

在这里我想要使用它的类.

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;
  }

}@H_404_2@
您还需要将成员放在类中,以便它确实实现接口:
class ResultPage implements ResultPageInterface {
    public entries: Array<any>;
    public page_number: number;
    public page_size: number;
    public total_entries: number;

    constructor() {
        this.entries = [];
    }
}@H_404_2@ 
 

您还可以将成员设为私有并使用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;
    }
}@H_404_2@
原文链接:https://www.f2er.com/angularjs/141930.html

猜你在找的Angularjs相关文章