Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i have class

C#
export class Options {

    //main properties

    valueField: any;
    labelField:any;
    sortField: string[];
    searchFields: string[];
    items: any[];
    currentResults: any[];
    delimiter: string;
    mode: SelectizeMode;
    selected: any;
    placholder: string;

    get hasOptions(): Boolean {
        return this.items ?  this.items.length > 0 : false;
    }


    constructor(_valueField?: string, _labelField?: string,
        _searchFields?: string[], _items?: any[], _currentResults?: any[],
        _selecetd?: any, _delimiter?: string, _sortField?: string[], _mode?: SelectizeMode, _placholder?: string) {


        this.valueField = _valueField;
        this.labelField = _labelField;
        this.sortField = _sortField || [this.valueField];
        this.searchFields = _searchFields || [this.labelField, this.valueField];
        this.items = _items;
        this.delimiter = _delimiter || ',';
        this.mode = _mode || SelectizeMode.single;
        this.selected = _selecetd;
        this.currentResults = _currentResults || [];
        this.placholder = _placholder || 'select...';
    }
}


i want to instate object of that class without having to pass all optional paramters

like c#

for example i want to like that

JavaScript
Options x =     Options(){
delimiter:','
}


What I have tried:

i made all constructor parameters as optional

create Interface instead of class it worked but produce another problem that i need new Instances so i had to make it class as can not take instance of interface
Posted
Updated 9-Aug-16 6:15am

1 solution

There is no easy way to do exactly what you want.
There is an alternative though which might fit your need.

Rather than creating a class you create an interface with all members optional.

JavaScript
export interface IOptions { 
 	valueField?: string; 
	labelField?: string;
	searchFields?: string[];
	...
}

Then the instantiation can be done from a simple object literal.
JavaScript
var options : IOptions =  {
	valueField: "aa",
	labelField: "bb"
};

It also works in methods:
JavaScript
var x = new class1({ valueField:"AA"});

class class1 {
 	valueField: string; 
	labelField: string;
  
	constructor(options: IOptions){
		this.valueField = options.valueField || "empty";	  
		this.labelField = options.labelField || "empty";	  
	}
}
 
Share this answer
 
Comments
Karthik_Mahalingam 14-Apr-17 8:24am    
5
Pascal Ganaye 19-Jun-17 9:40am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900