TypeScript 編譯配置 tsconfig.json compilerOptions 全解析
備註
由於 tsconfig.json 中的 compilerOptions 可配置選項實在是太多了,常常會忘記一些選項的用途,但 TypeScript 的官方文件有些選項要不是寫得太冗長就是太簡短。因此決定一次將所有 compilerOptions 透過 chatgpt 整理成一個大抄,方便我日後快速查詢。
- Type Checking
- allowUnreachableCode
- allowUnusedLabels
- alwaysStrict
- exactOptionalPropertyTypes
- noFallthroughCasesInSwitch
- noImplicitAny
- noImplicitOverride
- noImplicitReturns
- noImplicitThis
- noPropertyAccessFromIndexSignature
- noUncheckedIndexedAccess
- noUnusedLocals
- noUnusedParameters
- strict
- strictBindCallApply
- strictFunctionTypes
- strictNullChecks
- strictPropertyInitialization
- useUnknownInCatchVariables
- Modules
- Emit
- JavaScript Support
- Editor Support
- Interop Constraints
- Backwards Compatibility
- Language and Environment
- Compiler Diagnostics
- Projects
- Output Formatting
- Completeness
- Watch Options
- Reference
Type Checking
allowUnreachableCode
設定是否允許在程式中存在不可達的程式碼。
說明範例:
function example1() {
return;
console.log("這段程式永遠不會被執行"); // 如果 allowUnreachableCode 為 true,則不會報錯
}
allowUnusedLabels
設定是否允許在程式中存在未使用的標籤。
說明範例:
// 如果 allowUnusedLabels 為 true,則不會報錯
unusedLabel: for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
}
alwaysStrict
設定是否在 ECMAScript 嚴格模式下進行解析,在編譯輸出的 JavaScript 文件中強制啟用嚴格模式(插入 “use strict”)。
說明範例:
function example2() {
// "use strict"; 自動插入於此
let x = 1;
delete x; // 在嚴格模式下,這將會拋出錯誤
}
exactOptionalPropertyTypes
設定是否精確控制可選屬性類型,即是否允許 undefined 類型的值被賦給可選屬性。
說明範例:
interface User {
name: string;
age?: number;
}
const user1: User = { name: "Alice" };
const user2: User = { name: "Bob", age: undefined }; // 如果 exactOptionalPropertyTypes 為 true,則將報錯
noFallthroughCasesInSwitch
設定是否在 switch 語句中禁止 case 子句的穿透行為。
說明範例:
function example3(x: number) {
switch (x) {
case 1:
console.log("1");
// 沒有 break 語句會導致穿透,若 noFallthroughCasesInSwitch 為 true,則這將報錯
case 2:
console.log("2");
break;
default:
console.log("default");
}
}
noImplicitAny
設定是否在變數或參數的類型未明確指定時報錯。
說明範例:
function example1(x) {
// 如果 noImplicitAny 為 true,這將報錯,因為 x 的類型未指定
console.log(x);
}