我正在嘗試使用 tsc 將許多帶有雙問號的 JS 檔案轉換為 TypeScript。
但不幸的是 tsc 編譯器不理解 ??. 示例: this.x = typeof params.x == "string" ? this._processStringParam(params.x, "x") : params.x ?? 0;
它只是拋出錯誤:imageElement.js:70:96 - error TS1109: Expression expected。this.x = typeof params.x == "string" ? this._processStringParam(params.x, "x") : params.x ?? 0;
我不明白一件事。這個雙問號是轉換為 TS 的主要原因。那么我在 tsc 之前在 JS 中修復它有什么意義呢?
那么如何將此類 js 檔案轉換為 TypeScript 呢?
tsconfig.json 看起來像這樣:
{
"compilerOptions": {
"checkJs": false,
"module": "commonjs",
"target": "ES5",
"allowJs": true,
"rootDir": "./",
"baseUrl": "./",
"outDir": "./build",
"noStrictGenericChecks": true,
"skipLibCheck": true,
"strictFunctionTypes": false,
"lib": [
"es2015",
"dom"
]
},
"exclude": [
"./build/**"
]
}
uj5u.com熱心網友回復:
嘗試通過將目標更改為 "ES6"
這是因為在??ES2020 之后添加了or null 合并操作
uj5u.com熱心網友回復:
試試這個配置:
"compilerOptions": {
/* Language and Environment */
"target": "ES5", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"outDir": "dist", /* Specify an output folder for all emitted files. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
}
代碼ts:
console.log('coallescing nullish with undefined: ', undefined ?? 'compare with undefined');
console.log('coallescing nullish with null: ', null ?? 'compare with null');
console.log('coallescing nullish with valid data: ', 'with data' ?? 'compare with null or undefined');
將代碼轉譯為 js:
console.log('coallescing nullish with undefined: ', undefined !== null && undefined !== void 0 ? undefined : 'compare with undefined');
console.log('coallescing nullish with null: ', null !== null && null !== void 0 ? null : 'compare with null');
console.log('coallescing nullish with valid data: ', 'with data' !== null && 'with data' !== void 0 ? 'with data' : 'compare with null or undefined');
控制臺上的結果:
coallescing nullish with undefined: compare with undefined
coallescing nullish with null: compare with null
coallescing nullish with valid data: with data
此js代碼具有ES5兼容性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/368248.html
標籤:javascript 打字稿
下一篇:不能宣告泛型函式可能回傳null
