1

I'm using angular(2) and typescript. I'm using the moment library to convert dates so I have this function inside one of my utility classes:

static isoStringToDateObj(isoDateString: string): Date {
    // For unit tests and any environment where moment library is not present
    if (!moment) {
        return new Date(isoDateString);
    }
    return moment(isoDateString).toDate();
}

This works fine in the browser, but when I try to run my unit tests it throws the error: ReferenceError: Can't find variable: moment in karma-test-shim.js (line 16240)

The line it is referring to is the if (!moment) line.

  1. Why does it care if the variable does not exist in a statement that is only checking if the variable exists? It is not referencing any properties on it.
  2. I have declare var moment: any; at the top of the file that the function isoStringToDateObj is in, so why is it saying reference error when the variable is actually declared?
Alex Egli
  • 1,884
  • 2
  • 24
  • 43

1 Answers1

2

The only proper way to check if global variable does not exist is:

if (typeof moment === 'undefined') { ... }

ReferenceError: Can't find variable: moment

is runtime error, declare var moment: any cheats typing system to be silent about that but can't affect actual moment global in any way.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • 1
    Note: a much cleaner solution instead of `declare var foo: any` is `declare var foo: foo_type | undefined`, this keeps most of the type-checking while still allowing `undefined`. – biziclop Jul 04 '19 at 11:07