2

I'm using the library GoJS in my Angular project.

When I want to return a new Size() from gojs with only one parameter, the other one has to be NaN:

I'm doing something like new Size(NaN, height)

The constructor of Size() looks like this: constructor(w?: number, h?: number);

Why can't I use null instead of NaN ?

When using null the browser returns Error: Invalid arguments to Size constructor: null, 200

I don't have a problem to fix, I just don't understand why it wouldn't work with null

madidas
  • 23
  • 2
  • 2
    You can't pass in `null` but the type signature will let you pass in `undefined`, I don't know if GoJS will actually handle that case but the compiler should be satisfied. – Ferruccio Apr 22 '21 at 09:36
  • 1
    To expand on what Ferrucio said about, when you have a type like `w?: number` it is the same as saying `w: number | undefined`. So `null` isn't accepted, but `undefined` will be accepted. – cdimitroulas Apr 22 '21 at 10:41

1 Answers1

1

The reason is that NaN has type number, where null has type null. You cannot pass null where number is required. You could be doing that if type of this constructor would be constructor(w?: number | null, h?: number | null), then using it as new Size(null, null) would be type correct.

let a: number = NaN; // NaN is number
a = null; // error as null is not number

let b: number | null = NaN; // fine as before
b = null; // also fine as null is explicitly define in the type 

Also Error: Invalid arguments to Size constructor: null, 200 is runtime error, it means that inside the constructor code is checking arguments types by probably typeof and raise this exception if any of the arguments will not be number.

Maciej Sikora
  • 19,374
  • 4
  • 49
  • 50