[英]Typescript fails to transpile when leaving out spread of undefined {…undefined}
我有一个 typescript 项目。 在一些 typescript 文件中,我包含一个名为 config.js 的普通 javascript/node 文件,如下所示:
'use strict';
module.exports = {
a: 'a',
b: 'b',
c: 'c',
};
当我运行tsc
时,转译失败并出现错误,该错误引用了导入此 config.js 文件的文件。 该错误似乎指向一些与 typescript 类型相关的问题:
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);
该错误看起来像是应用程序级别的错误,但对我来说完全是个谜,当我将 config.js 更改为:
'use strict';
module.exports = {
a: 'a',
b: 'b',
c: 'c',
...undefined
};
转译步骤成功。
typescript 文件中 config.js 的导入如下所示: import CONFIG from '../config';
现在我的问题是:在对我的 typescript 代码一无所知的情况下,添加 undefined ( ...undefined
) 的扩展怎么会导致编译成功? 据我所知{...undefined}
导致一个空的 object。 是否有一些我不知道的奇怪错误或边缘情况?
注意:我在 object 中的哪个位置放置 undefined: { a: 1, ...undefined, b: 2 }
的展开也无关紧要,这也使编译成功,只有将其完全省略会使其失败。
评论里的人是对的。
如果我将 config.js 文件转换为定义了显式类型的 typescript 文件(如下所示),那么我的项目将成功转译。 它确实看起来像使用未定义的传播( {...undefined }
)导致 typescript 不再推断 plain.js 文件中的类型,然后在 typescript 文件本身中使用它们时也不会抱怨它们。
另一种方法是继续使用 plain.js 文件并提供 d.ts 文件来指定类型。
const CONFIG: {
a: string,
b: string
} = {
a: 'a',
b: 'b'
}
export default CONFIG;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.