简体   繁体   中英

Typescript fails to transpile when leaving out spread of undefined {…undefined}

I have a typescript project. In some of the typescript files I include a plain javascript/node file called config.js which looks like this:

'use strict';

module.exports = {
  a: 'a',
  b: 'b',
  c: 'c',
};

When I run tsc the transpilation fails with an error that refer to files that import this config.js file. The error seems to point at some typescript type related problem:

src/db/index.ts:138:26 - error TS2345: Argument of type 'string' is not assignable to parameter of type '"source" | "command" | "training" | "page"'.

138   await mutateCollection(CONFIG.commandCollectionName, mutateCommandCollection, commands);

The error looks like an application level error but what is a total mystery to me is that when I change my config.js to:

'use strict';

module.exports = {
  a: 'a',
  b: 'b',
  c: 'c',
  ...undefined
};

The transpilation step succeeds.

The import of the config.js in the typescript file looks like this: import CONFIG from '../config';

Now my question is: without knowing anything about my typescript code, how could adding a spread of undefined ( ...undefined ) ever cause the transpilation to succeed? As far as I know {...undefined} results in an empty object. Is there some weird bug or edge case that I don't know of?

Note: it doesn't matter where in the object I put the spread of undefined: { a: 1, ...undefined, b: 2 } also makes the transpilation succeed, only leaving it out entirely will make it fail.

The people in the comments were right.

If I turn the config.js file into a typescript file with explicit types defined (as can be seen below), then my project transpiles succesfully. It indeed looks like using a spread of undefined ( {...undefined } ) causes typescript to not infer the types in the plain.js file anymore and then also not complain about them when used in the typescript files themselves.

An alternative would be to keep using a plain.js file and provide a d.ts file to specify the types.

const CONFIG: {
  a: string,
  b: string
} = {
  a: 'a',
  b: 'b'
}
export default CONFIG;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM