"Cannot read property" when using deferConfig of node-config in "TypeScript

244 views Asked by At

I'm using node-config in TypeScript.
I have the code like below:
config/default.ts:

import {deferConfig} from 'config/defer';
export default {
  service: {
    url: 'http://localhost',
    errorUrl: deferConfig(function() {
      console.info('config before defer:', this);
      return `${this['service']['url']}/error.html`;
    }),
  },
};

src/demo.ts:

import config from 'config';
console.info('resulting config: ', config)

It works fine when I run my code with ts-node.

$ npx ts-node ./src/demo.ts
config before defer: { service: { url: 'http://localhost', errorUrl: [Getter] } }
resulting config:  Config {
  service: { url: 'http://localhost', errorUrl: 'http://localhost/error.html' }
}

However, if I run the code compiled with tsc, I get

$ NODE_CONFIG_DIR=./build/config ./build/src/demo.js
config before defer: {
  default: { service: { url: 'http://localhost', errorUrl: [Getter] } }
}
.../build/config/default.js:9
            return `${this['service']['url']}/error.html`;
                                     ^
TypeError: Cannot read property 'url' of undefined

The value of this has an extra level of default.
Why the behavior is inconsistent for the ts and the js code? If I change export default to export =, it works for both ts and js code.
However, the document of node-config asks me to use export default.
Should I use export = instead?

0

There are 0 answers