Paul Redmond
Paul Redmond

Reputation: 3296

TypeScript - Pass object literal to class constructor

Can you pass default values to a class constructor? Here, last returns undefined.

class greatFunction {
    options: {
        names:  {first: 'Joe', last: 'Bloggs'}
    }
    constructor(options) {
        console.log(options.names.first + ' ' + options.names.last);        
    }
}

Called:

new greatFunction({
    names: {
        first: 'Paul'
    }
});

Upvotes: 1

Views: 8717

Answers (3)

Andy-Delosdos
Andy-Delosdos

Reputation: 3720

You do need to pass something to the function, so one option would be to try something like this:

class greatFunction {
    defaultOptions = {
        names: { first: 'Joe', last: 'Bloggs' }
    }
    constructor(options) {
        if (options == null)
            options = this.defaultOptions;
        console.log(options.names.first + ' ' + options.names.last);
    }
} 

You can then create a new greatFunction using:

let x = new greatFunction(null)

Or:

let y = new greatFunction({ names: { first: 'Test', last: 'Blah' } });

Alternatively, don't do it using the constructor, and use a property after initialising. For example:

class greatFunction {
    public options = {
        names: { first: 'Joe', last: 'Bloggs' }
    }
    constructor() { }
    doSomething() {
        console.log(this.options.names.first + ' ' + this.options.names.last);
    }
} 

and then use with:

let x = new greatFunction();
x.options = { names: { first: 'Test', last: 'Blah' } };
x.doSomething();

Upvotes: 0

P Varga
P Varga

Reputation: 20219

Try setting default values:

class GreatFunction {
  options: {
    names:  {first: 'Joe', last: 'Bloggs'}
  }
  constructor({names: {first=this.options.names.first: firstName, last=this.options.names.last: lastName}}) {
    console.log(`${firstName} ${lastName}`)        
  }
}

Alternatively, use a library, for example lodash.defaults() seems to fit your use case.

Upvotes: 0

Theophilus Omoregbee
Theophilus Omoregbee

Reputation: 2503

instead of doing that why dont you create an interface like this

interface names { 
      firstname:string;
      lastname ?: string;
  }

Since you can't create make a property of a parameter optional.

Or you do the hard way which is like this

interface IOptions{
names:INames;
     }

 interface  INames {
    first:string;
    last?:string;
  }

   class greatFunction{

        constructor (options:IOptions){
          options.names.last = options.names.last?options.names.last:'Default';
       console.log(options.names.first + ' ' + options.names.last)
    }
 }

   new greatFunction({names:{first:'Theophilus'}});

It should return the default in console

Upvotes: 3

Related Questions