Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/66063806/typescript-fails-to-transpile-when-leaving-out-spread-of-undefined-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...