# Google TypeScript Style Guide 筆記 > [Google TypeScript Style Guide](https://google.github.io/styleguide/tsguide.html) ## 筆記備註 正例會用綠底包裹,反例會用紅底包裹,未包裹的內容皆為正例。 :::success 這是正例 ::: :::danger 這是反例 ::: 如果是規則的例外會使用藍底包裹 :::info 這是例外 ::: ## Syntax ### Identifiers * class, interface, type, enum, decorator, type 使用大寫開頭的 camel case * 變數, 函數, parameter, arugment, module 的 alias 使用小寫開頭的 camel case * 全域常數, enum 的 value 使用全大寫,底線分隔 #### Abbreviations 把縮寫視為一個單字,不要因為他是縮寫就全大寫,例如 :::danger Don't ```typescript lodaHTTPURL() ``` ::: :::success Do ```typescript loadHttpUrl() // prefer ``` ::: #### Dollar sign 變數不要用 `$`。 :::info 例外:第三方套件的慣例,如 RxJS 的 Observable。 ::: #### Type parameters 如 `Array<T>`,可使用大寫的 camel case 或單獨的 `T` #### Test names > 不確定 測試用函數的命名規則使用 Closure testSuites 或 xUnit-style,如 `testX_whenY_doesZ()` #### _ prefix/suffix 變數不得使用底線前綴/後綴,包含單獨的 `_`。 如果是想取得集合中的部分元素,只需要多加額外的 `,`,例如: :::success Do ```typescript const [a, , b] = [1, 2, 3]; // a -> 1, b -> 3 ``` ::: :::danger Don't ```typescript const [a, _, b] = [1, 2, 3]; ``` ::: #### Constants 全大寫底線分隔的常數代表不應被變動,即便他 "技術上" 可以被變動 (如 object,宣告為 `const` 時他的 value 依舊能被變更)。 在 class 的常數 property 宣告為 `static readonly`。 #### Aliases 當建立一個 local scope 的變數,用做於既有的 symbol 的 alias,該變數必須照著來源的名稱、格式 (camel case, snake case...),如果來源被宣告為 `const`,則 alias 必須被宣告為 `const` 或 `readonly`。 ```typescript class Teapot { readonly BrewStateEnum = BrewStateEnum; readonly CAPACITY = CAPACITY; } ``` > 註:例如在 Angular component class 中要取得撰寫在其他用於存放靜態資料的 .ts 檔中的變數,以讓 template HTML 能取得時,會有以下寫法: > ```typescript > readonly CONSTANT = CONTANT; > ``` #### Naming style 命名不得包含 type 的資訊 (即匈牙利命名法),如 `fooArr`。 :::info 除了慣例,如 RxJS 的 Observable 慣例上會有 `$` 後綴。 ::: #### Descriptive names 變數命名必須清楚明白的表示其意義,不要使用縮寫。 :::info 例外:scope 為 10 行以下的變數可使用簡短的變數名稱 (縮寫、單一字元)。 ::: ### File encoding: UTF-8 非 ASCII 字元直接使用實際的字元,不要用它的 unicode。 若是無法打出來的字元可使用 unicode (`\ufeff`),必須註解描述它是什麼。 ### No line continuations 不得使用 line continuation,即 `\`,即使 ES5 已經支援它了,但還是有可能有非預期的錯誤。 :::success Do ```typescript const LONG_STRING = 'This is a very long string that far exceeds the 80 ' + 'column limit. It does not contain long stretches of spaces since ' + 'the concatenated strings are cleaner.'; ``` ::: :::danger Don't ```typescript const LONG_STRING = 'This is a very long string that far exceeds the 80 \ column limit. It unfortunately contains long stretches of spaces due \ to how the continued lines are indented.'; ``` ::: > 進度暫存 https://google.github.io/styleguide/tsguide.html#comments-documentation