2

I have class in Angular 6

export class classXY{
  xValue: number;
  yValue: number;
  xDate: Date;
  yDate: Date;
  xName?: string;
  yName?: string;
}

in my code, I need to check the properties that have type number.

let obj: ClassXY;
obj.xValue=1;
obj.yValue=null;
obj.xDate= new Date();
obj.yDate= null;
obj.xName= "test";
obj.yName= null;

    for (var key in obj) {
      if ((obj[key] == null) && (typeof obj[key] === "number"))
        obj[key] = -1;
}

typeof obj["yValue"] value is null and typeof "yValue" is string, while I need to return the type of property number. Same for instanceof

How I check the primitive type of property of an object?

Alaa'
  • 487
  • 3
  • 7
  • 16

1 Answers1

2

TypeScript is compiled down to JavaScript and JavaScript is a dynamically typed language. This means that the type of a variable can change during the runtime as visible here:

let a = null;
console.log(typeof a);

a = 5;
console.log(typeof a);

a = 'hello';
console.log(typeof a);

In your case, your condition will never evaluate to true, since if obj[key] is null, then its type can't be number:

if ((obj[key] == null) && (typeof obj[key] === "number"))

Here is a way to do what you want using property initializers to provide default values to your class fields and a function that compare those fields to the default value assigned when constructing an object of your class:

function setDefaultValues(obj, defaultValues, valueToCheck) {
  for (const prop in obj) {
    if (defaultValues[prop] === valueToCheck && obj[prop] === null) {
      obj[prop] = valueToCheck;
    }
  }
}

class A {
  x = -1; // default value
  y = -1; // default value
  z = 'hello';
}

const a = new A();
a.y = null; // a.y will be replaced by -1 later
console.log(a);

setDefaultValues(a, new A(), -1); // check all -1 fields on `new A()`, if null on `a`, then set to -1
console.log(a);
jo_va
  • 13,504
  • 3
  • 23
  • 47
  • 1
    thank you. I got the idea, and I gave all my properties a default value in the class and I used typeof of the defaultValue and it worked if (t**ypeof** defaultValues[prop] === "number" && obj[prop] === null) obj[prop] = -99; – Alaa' May 01 '19 at 06:17