[英]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.