user2902037 user2902037 - 4 months ago 15
AngularJS Question

TypeScript - Not able to create object of a class using new operator

Object creation is happening without error:

let paginationParams: Common.Models.PaginationModel = {
PageNumber: this.pageNumber,
PageSize: this.pageSize,
SearchText: this.denominationFilter,
Ascending: true
};


try to create the object like:

let pagParams = new Common.Models.PaginationModel(
this.pageNumber,
this.pageSize,
true,
this.denominationFilter);


Getting error:

enter image description here

Answer

There is a snippet at TS playground

I would say, that we can think about this interface and its implementation

namespace Common.Models
{
    export interface IPaginationModel {
        PageNumber: number;
        PageSize: number;
        SearchText: string;
        Ascending: boolean;
    }
    export class PaginationModel implements IPaginationModel {
        constructor(
            public PageNumber: number,
            public PageSize: number,
            public SearchText: string,
            public Ascending: boolean
        ){}
    }
}

and then we can use it like this

// we use an Interface to assure that the type is as it should be
// we create object which fits to IPaginationModel structure
let paginationParams: Common.Models.IPaginationModel = {
    PageNumber: this.pageNumber,
    PageSize: this.pageSize,
    SearchText: this.denominationFilter,
    Ascending: true
};

// here we use a class
// to call its constructor
let pagParams = new Common.Models.PaginationModel(
    this.pageNumber,
    this.pageSize,
    this.denominationFilter,
    true);

// and we can even use class as interface (as the first example)
let paginationParamsAsClassAPI: Common.Models.PaginationModel = {
    PageNumber: this.pageNumber,
    PageSize: this.pageSize,
    SearchText: this.denominationFilter,
    Ascending: true
};

So, we can use interface and class as a type, while building plain JS object (first and third example) or we can use the class constructor to build such instance.

Check it here

Comments