
React
使用函數組件
始終使用TSX函數組件。 不要使用帶有const的默認 import,因為更難讀取和使用代碼完成進行導入。
屬性
Create the type of the props and call it(ComponentName)Props if there’s no need to export it.
Use props destructuring.
Refrain from using React.FC or React.FunctionComponent to define prop types
JSX元素中無單一變量參數展開
避免在JSX元件中使用單一變量展開,例如{...props}。 此做法通常導致代碼可讀性降低,維護難度增加,因為不清楚組件接收了哪些參數。
- 一目了然,可以清楚地知道傳遞了哪些參數,從而使其更容易理解和維護。
- 它有助於防止組件之間因過於緊密的參數耦合。
- 列出參數可以使查找拼寫錯誤或未使用的參數更容易通過Lint工具辨識。
JavaScript
使用空值合併運算符 ??
使用可選鏈接運算符 ?.
TypeScript
使用type而非interface
始終使用type而非interface,因為它們幾乎總是重疊且type更具靈活性。
使用字符串字面值替代枚舉
字符串字面值是TypeScript中處理類枚舉值的首選方法。 這些內容更容易擴展,并且在使用Pick和Omit時提供更好的開發體驗,尤其是在代碼完成方面。 你可以在這裡看到TypeScript為何建議避免使用枚舉。GraphQL和內部庫
您應該使用GraphQL代碼生成的枚舉。 使用內部庫時最好使用枚舉,這樣內部庫就無需公開與內部API無關的字符串字面值類型。 示例:樣式
使用StyledComponents
使用styled-components對組件進行樣式設計。主題設計
為大多數組件的樣式運用主題是首選方法。計量單位
避免在樣式組件中直接使用px或rem值。 所需的值通常在主題中已經定義了,因此建議利用主題來達到這些目的。
顏色
避免引入新顏色;相反地,使用來自主題的現有調色板。 如果有調色板不對應的情況,請留下評論以便團隊解決。強制不使用類型導入
避免類型導入。 要強制執行此標準,ESLint規則檢查並報告任何類型導入。 這有助於保持TypeScript代碼的一致性和可讀性。為何不使用類型導入
- 一致性:通過避免類型導入並對類型和值導入使用單一方法,代碼庫在其模塊導入風格上保持一致。
- 可讀性:不使用類型導入提高了代碼可讀性,因為它清楚地表明您何時正在導入值或類型。 This reduces ambiguity and makes it easier to understand the purpose of imported symbols.
- Maintainability: It enhances codebase maintainability because developers can identify and locate type-only imports when reviewing or modifying code.
ESLint規則
An ESLint rule,@typescript-eslint/consistent-type-imports, enforces the no-type import standard. 此規則會為任何類型導入違規情況生成錯誤或警告。
Please note that this rule specifically addresses rare edge cases where unintentional type imports occur. TypeScript itself discourages this practice, as mentioned in the TypeScript 3.8 release notes. In most situations, you should not need to use type-only imports.
To ensure your code complies with this rule, make sure to run ESLint as part of your development workflow.