Øle Bjarnstroem Øle Bjarnstroem - 1 month ago 12
TypeScript Question

Typescript / Angular 2: Property is missing in type

I'm still quite new to Typescript and have trouble wrapping my head around interfaces. As I understand an interface is a type description or a contract for a class. It allows me to define, which properties a class can have and of which type they are. I try to implement that, but always get this error:

error TS2420: Class 'ResultPage' incorrectly implements interface 'ResultPageInterface'.
Property 'entries' is missing in type 'ResultPage'.


Here is the code for the interface

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

export class ResultPage implements ResultPageInterface {}


And here the class where I want to use it.

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

}

Answer

You need to put the members in the class as well so that it will indeed implement the interface:

class ResultPage implements ResultPageInterface {
    public entries: Array<any>;
    public page_number: number;
    public page_size: number;
    public total_entries: number;

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

You can also have the members private and use getters:

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