Search code examples
node.jsangulartypescript

how to handle: Assigned expression type number | undefined is not assignable to type number


I have this class:

  id: number;
  name: string;
  description: string;
  productsSet: Set<Products>;

constructor(
id?: number,
name?: string,
description?: string,
productsSet?: Set<Products>
  )    {
   this.id = id;
    this.name = name;
     this.description = description;
    this.productsSet = productsSet;
    }

I've read about 3 different solutions to this problem, i can either allow undefined, use the null operator or set a default value, but what is the best practice in this case?


Solution

  • the best approach i found is to just give default values to the parameters:

     constructor(
      id: number = 0,
      name: string = '',
      description: string = '',
      productsSet: Set<Products> = new Set()
     ) {
      this.id = id;
      this.name = name;
      this.description = description;
      this.productsSet = productsSet;
     }