How to start Angular2 prototype with an object literal

export abstract class GridColumn {
    public field?: string;
    public sortField?: string;
    public header?: string;
    public footer?: string;
    public sortable?: any = true;
    public editable?: boolean = false;
    public filter?: boolean = true;
    public filterMatchMode?: string = 'contains';
    public filterPlaceholder?: string;
    public style?: any;
    public styleClass?: string;
    public hidden?: boolean = false;
    public selectionMode?: string = 'multiple';
    public frozen?: boolean;
}

For instance, by doing this, you will only receive an object with those specific properties.

private gridConf: GridColumn = <GridColumn>{
    field: "test2",
    header: "Test2",
    filter: true,
    filterMatchMode: "contains",
    filterPlaceholder: "Search from Test",
    sortable: true,
    selectionMode: "single"
};

The objective is to create an object of type GridColumn that includes all the declared properties along with their default values.
The following approach does not achieve this:

private gridConf: GridColumn = GridColumn({
    field: "test2",
    header: "Test2",
    filter: true,
    filterMatchMode: "contains",
    filterPlaceholder: "Search from Test",
    sortable: true,
    selectionMode: "single"
});

Using a constructor would require specifying all properties in order, which is not ideal.

The ultimate goal is to have the flexibility to define and utilize default and/or specified properties in any order like this:

private columns: Array<GridColumn> = [
    <GridColumn>{
        field: "test",
        selectionMode: "single",
        filter: true,
        filterMatchMode: "contains",
        filterPlaceholder: "Search from Test",
        sortable: true,
        header: "Test"

    },
    <GridColumn>{
        field: "test2",
        header: "Test2",
        filter: true,
        filterMatchMode: "contains",
        filterPlaceholder: "Search from Test",
        sortable: true,
        selectionMode: "single"
    }
];

The closest workaround found was removing the abstract keyword and adding a constructor where fields refer to itself:

public constructor(
    fields?: GridColumn) {
    if (fields) Object.assign(this, fields);
}

Answer №1

While it may not be the most conventional method, there is a workaround that could potentially achieve what you're looking for. Keep in mind that this approach may not adhere to best practices, but if you're determined to make it work, here's how you can go about it. It's worth noting that default values will only be initialized if you use new GridColumn() on a non-abstract class:

GridColumn

export class GridColumn implements IGridColumn {

    public sortable: boolean = true;
    public editable: boolean = false;
    public filter: boolean = true;
    public filterMatchMode: string = 'contains';
    public hidden: boolean = false;
    public selectionMode: string = 'multiple';

    public field: string;
    public sortField: string;
    public header: string;
    public footer: string;
    public filterPlaceholder: string;
    public style: any;
    public styleClass: string;
    public frozen: boolean;

    constructor(data: IGridColumn = {}){
       Object.assign(this, data);
    }
}

IGridColumn

export interface IGridColumn {
    public field?: string;
    public sortField?: string;
    public header?: string;
    public footer?: string;
    public sortable?: boolean;
    public editable?: boolean;
    public filter?: boolean;
    public filterMatchMode?: string;
    public filterPlaceholder?: string;
    public style?: any;
    public styleClass?: string;
    public hidden?: boolean;
    public selectionMode?: string;
    public frozen?: boolean;
}

Usage

private columns: Array<GridColumn> = [
    new GridColumn(<IGridColumn>{
        field: "test",
        selectionMode: "single",
        filter: true,
        filterMatchMode: "contains",
        filterPlaceholder: "Search from Test",
        sortable: true,
        header: "Test"

    }),
    new GridColumn(<IGridColumn>{
        field: "test2",
        header: "Test2",
        filter: true,
        filterMatchMode: "contains",
        filterPlaceholder: "Search from Test",
        sortable: true,
        selectionMode: "single"
    })
];

It's important to reiterate that this solution may deviate from standard best practices. Additionally, starting an interface name with an I is generally discouraged :D

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Specifying the return type of a function as a combination of the types of the input arguments

Is there a way to safely implement the given function in TypeScript without using unsafe casts or an extensive number of function overloads with various input permutations? interface Wrapped<T> { type: string; data: T; } interface WrappedA&l ...

Using Typescript literal types as keys in an indexer is a common practice

Can we create a TypeScript literal type that acts as a string key in an indexer? type TColorKey = 'dark' | 'light'; interface ColorMap { [period: TColorKey]: Color; } But when attempting this, the following error is generated: An ...

HTML not updating after a change in properties

My template is structured as a table where I update a column based on a button click that changes the props. Even though the props are updated, I do not see the template re-rendered. However, since I am also caching values for other rows in translatedMessa ...

Differences between RxJs Observable<string> and Observable<string[]>

I'm struggling to grasp the concept of RxJS Observables, even though I have utilized the observable pattern in various scenarios in my life. Below is a snippet of code that showcases my confusion: const observable: Observable<Response> = cr ...

What is the best way to store a small number of files in the state

I have recently implemented Drag and Drop functionality, and now I am facing an issue where I need to save a few files in state. const [uploadedFiles, setUploadedFiles] = useState<any[]>([]); const onDropHandler = async (e: React.DragEvent<HTMLDi ...

Creating dynamic HTML elements using ngFor within AngularJS allows for increased flexibility and customization on the

I'm a newcomer to Angular 5 and I'm looking to retrieve HTML elements from a .ts file and dynamically add them to an HTML file using ngFor. I attempted to use [innerHtml] for this purpose, but it was not successful and returned [object HTMLSelect ...

Exploring the new possibilities of Angular 5: Enhanced REST API service with paginated data and object mapping capabilities

After implementing pagination in my REST API backend, I now need to update my Angular services to accommodate the changes. Instead of simply returning an array of objects, the API will now return JSON responses structured like this: { "count": 0, ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. Below is my API code: Here is the service code: This section includes the function calling code: Additionally, this is the model being used The API C# model c ...

Align the ion content (or text or label) to the center vertically

I am striving to achieve a similar look as shown in the following images: However, I am currently at this stage: Please note that the first image showcases a bootstrap form, while the second image displays my design using ionic. Although I prefer not to ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

What could be the reason for the absence of a TypeScript error in this situation?

Why is it that the code below (inside an arbitrary Class) does not show a TypeScript error in VSCode as expected? protected someMethod (someArg?: boolean) { this.doSomething(someArg) } protected doSomething (mustBePassedBoolean: boolean) { /* ... * ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

Select the data you wish to showcase on Highcharts

When it comes to loading a CSV into Highcharts with Angular, my usual approach is as follows: export class OutputGraphComponent implements OnInit { public options: any = { chart: { type: 'column' }, data: { csvURL: path.to ...

Can you modify a specific column in a table using mat-table in Angular material?

For my project, I am utilizing Angular Material's table to present data in a tabular format. However, due to a new requirement, I now need to enable in-line editing for the last 2 columns alongside highlighting another column when the user clicks on t ...

Configuring the parameters property for a SSM Association in AWS CDK

I am working on utilizing the AWS Systems Manager State Manager to automate shutting down an RDS instance at 9PM using a cron job. Currently, I am constructing the CloudFormation template with the help of AWS CDK. While going through the AWS CDK documenta ...

Traverse through an array of objects with unspecified length and undefined key names

Consider the following object arrays: 1. [{id:'1', code:'somecode', desc:'this is the description'}, {...}, {...}] 2. [{fname:'name', lname:'last name', address:'my address', email:'<a h ...

What is the best way to detect component errors on the server with Angular Universal?

Here is a snippet of my server code that renders the Angular home.component: app.get("*", (req, res) => { res.render( `../${CLIENT_DIST_DIR}/index`, { req: req, res: res, providers: [ ...

Verifying TypeScript errors before each commit in a Vue application

We have set up a git hook in our app using Husky for pre-commit actions. Whenever someone commits code, it triggers the pre-commit code - #!/bin/sh . "$(dirname "$0")/_/husky.sh" export NVM_DIR="$HOME/.nvm" [ -s "$NVM_ ...

Angular 2: Enhancing Tables

I am looking to create a custom table using Angular 2. Here is the desired layout of the table: I have a Component that provides me with data export class ResultsComponent implements OnInit { public items: any; ngOnInit() { this.items = [&apos ...