Search code examples
typescriptnullnumbersnangojs

Why do I have to use NaN in a constructor and can't use null? typescript


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


Solution

  • 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.