20 個編寫清晰高效的 TypeScript 代碼的技巧
編寫干凈、清晰且高效的 TypeScript 代碼對于維護可擴展和可維護的代碼庫至關(guān)重要。
今天這篇文章將與您分享20個實用技巧的代碼示例,以幫助您提高 TypeScript 開發(fā)技能并生成高質(zhì)量的代碼。
1.使用顯式類型而不是“any”
盡可能避免使用 any 類型,因為它會破壞 TypeScript 的優(yōu)勢。相反,顯式定義變量、函數(shù)和參數(shù)的類型。
這樣做:
function add(a: number, b: number): number { return a + b;}
而不是這個:
function add(a: any, b: any): any { return a + b;}
2. 在 tsconfig.json 中啟用“嚴格”模式
啟用“嚴格”模式可確保 TypeScript 執(zhí)行廣泛的類型檢查,從而在開發(fā)過程的早期捕獲潛在的錯誤。
{ “compilerOptions”: { “strict”: true }}
3.使用只讀數(shù)組
利用只讀來防止對對象和數(shù)組的意外修改。
這樣做:
const person: Readonly<{ name: string; age: number }> = { name:
'Alice', age: 30 };person.age = 31; // Error: Cannot assign to 'age' because it
is a read-only propertyconst numbers: ReadonlyArray = [1, 2,
3];numbers.push(4); // Error: Property 'push' does not exist on type 'readonly
number[]'
而不是這個:
const person = { name: 'Alice', age: 30 };person.age = 31; // Allowedconst
numbers = [1, 2, 3];numbers.push(4); // Allowed
4. 使用解構(gòu)來提取屬性
解構(gòu)可以使您的代碼更簡潔、更易于閱讀。
這樣做:
function printPersonDetails({ name, age }: { name: string; age: number }) {
console.log(`Name: ${name}, Age: ${age}`);}
而不是這個:
function printPersonDetails(person: { name: string; age: number }) {
console.log(`Name: ${person.name}, Age: ${person.age}`);}
5. 數(shù)組泛型優(yōu)于類型轉(zhuǎn)換
使用數(shù)組泛型來指定數(shù)組中元素的類型,而不是類型轉(zhuǎn)換。
這樣做:
const numbers: Array = [1, 2, 3];const firstNumber: number =
numbers[0];
而不是這個:
const numbers: any[] = [1, 2, 3];const firstNumber: number = numbers[0] as
number;
6. 使用枚舉作為常量
使用枚舉來表示一組相關(guān)常量,以提高代碼的可讀性和可維護性。
這樣做:
enum Fruit { APPLE = 'apple', BANANA = 'banana', ORANGE = 'orange',}
而不是這個:
const FRUIT_APPLE = 'apple';const FRUIT_BANANA = 'banana';const FRUIT_ORANGE
= 'orange';
7. 對于對象形狀,優(yōu)先選擇接口而不是類型別名
在定義對象的形狀時使用接口來利用其可擴展性。
這樣做:
interface Person { name: string; age: number;}
而不是這個:
type Person = { name: string; age: number;};
8. 對可配置對象使用可選屬性
在接口中使用可選屬性可以在配置對象時實現(xiàn)靈活性。
??這樣做:
interface Person { name: string; age?: number;}
而不是這個:
interface Person { name: string; age?: number;}
9. 使用 TypeScript 的實用類型
利用 TypeScript 的內(nèi)置實用程序類型(例如 Partial、Pick 和 Omit)來避免不必要的重復并簡化代碼。
interface Person { name: string; age: number; address: string;}type
PartialPerson = Partial; // Makes all properties optionaltype PersonName
= Pick; // Extracts a subset of propertiestype PersonWithoutAge
= Omit; // Removes a property
10. 對多種可能的類型使用聯(lián)合類型
使用聯(lián)合類型指定一個變量可以保存多種類型的值。
這樣做:
function formatInput(input: string | number) { return `Input: ${input}`;}
而不是這個:
function formatInput(input: string | number) { return `Input: ${input}`;}
11.利用交叉類型來組合類型
使用交集類型將多種類型合并為單一類型。
這樣做:
interface Shape { color: string;}interface Circle { radius: number;}interface
Rectangle { width: number; height: number;}type RedCircle = Shape &
Circle;type RedRectangle = Shape & Rectangle;const redCircle: RedCircle = {
color: 'red', radius: 5 };const redRectangle: RedRectangle = { color: 'red',
width: 10, height: 20 };
而不是這個:
interface Employee { name: string; age: number;}interface Manager { teamSize:
number;}type EmployeeManager = Employee & Manager;const employee:
EmployeeManager = { name: 'John Doe', age: 30, teamSize: 5 };
12. 使用類型保護進行類型斷言
使用類型保護來縮小條件塊中變量的類型范圍。
這樣做:
function formatValue(value: string | number): string { if (typeof value ===
'number') { return value.toFixed(2); } else if (typeof value === 'string') {
return value.toUpperCase(); } else { throw new Error('Invalid value'); }}
而不是這個:
function processValue(value: string | number): string { if (typeof value ===
'number') { return value.toFixed(2); } else { return value.toUpperCase(); }}
13.更喜歡函數(shù)式編程技術(shù)
利用函數(shù)式編程技術(shù)(例如不變性和純函數(shù))來提高代碼清晰度并減少副作用。
這樣做:
const sum = Array.from({ length: 10 }, (_, i) => i + 1).reduce((acc, val)
=> acc + val, 0);
而不是這個:
let sum = 0;for (let i = 1; i <= 10; i++) { sum += i;}
14. 使用空合并運算符 (??)
空值合并運算符 (??) 提供了一種處理空值或未定義值的簡潔方法。
這樣做:
const defaultValue = value ?? 'Default';
而不是這個:
const defaultValue = value !== null && value !== undefined ? value :
'Default';
15. 使用可選鏈接 (?.)
可選鏈接 (?.) 簡化了對可能未定義或為 null 的對象屬性的訪問。
這樣做:
const username = user?.profile?.name;
而不是這個:
const username = user && user.profile &&
user.profile.name;
16.杠桿類型推斷
利用 TypeScript 的類型推斷功能來避免冗余的類型注釋。
這樣做:
const name = 'Alice';
而不是這個:
const name: string = 'Alice';
17.避免深層嵌套
利用 TypeScript 的類型推斷功能來避免冗余的類型注釋。
這樣做:
function process() { // Code}if (condition1 && condition2 &&
condition3) { process();}
而不是這個:
if (condition1) { if (condition2) { if (condition3) { // Code } }}
18.遵循一致的命名約定
遵守變量、函數(shù)和類的一致命名約定,以提高代碼的可讀性。使用傳達實體目的的描述性名稱。
19.模塊化你的代碼
將代碼分解為更小的模塊,每個模塊負責特定的功能。這提高了可重用性和可維護性。
20.寫下清晰簡潔的評論
添加注釋來解釋復雜的算法、重要的決策或邊緣情況。避免僅僅重述代碼的過多注釋。
總結(jié)
編寫清晰高效的 TypeScript 代碼需要練習、注重細節(jié)并遵守最佳實踐。本文分享的20個技巧,將能夠幫助您生成更易于理解、維護和擴展的高質(zhì)量代碼。最后,祝編程快樂!