简体   繁体   中英

TypeScript: Optional params in Class

I have a moderately big class with a lot of different attributes. Since there are a lot of them, making a constructor for the class would be pretty clumsy (imagine having new CLassObj(par1, par2, par3, par4, par5, par6, par7, ...pars) in your code. It'd be impossible to remember the order, so I usually initialize it like this:

{
    movie: this.movie,
    row: 10,
    seat: 12,
    cashPrice: 170,
    discount: 0,
    bonusesPrice: 4200,
    is3D: false,
    isVR: false,
    includesGlasses: false,
    promocode: ''
  }

and that's okay. But If I have a method inside the class, then I'd need to redefine it too!

Is there any way to make optional params without making a constructor? Or is there a sane way of making constructor take the object?

Here is a sample of how to create a class with optional parameters :

export class User {
  constructor(
    public id?: string,
    public fullName?: string,
  ) {}
}

you can now call it with

let user = new User();
let user = new User('ID1');
let user = {};
let user = { id: 'ID1' }; // Your IDE will give you completion in that case
// And so on ...

You can use a Partial<T> as parameter to the constructor. This allows for an object literal that optionally specifies any member of the class:

class BigClass {
    movie: string;
    row: number;
    seat:number;
    cashPrice: number;
    discount: number;
    bonusesPrice: number;
    is3D: boolean;
    isVR: boolean;
    includesGlasses: boolean;
    promocode: string;
    public constructor (cfg: Partial<BigClass>){
        Object.assign(this, cfg);
    }
    method (){

    }
}

var d = new BigClass({
    is3D: true
});

There are quite a few solutions to this problem.

You could use deconstructing: C:

You could use some design patterns like builder: C:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM