This is a living document outlining the styleguide for JavaScript/TypeScript projects within the commonlabs ID umbrella. Our styleguide is mostly derived from the Airbnb JavaScript styleguide, with changes made to accomodate TypeScript projects.
Use filenames that are as clear and standard as possible. Strive for names no longer than 2-3 words, with unabbreviated phrases.
- Good example:
findPathOptions.ts - Bad example:
fpOpts.ts
All test files must be written either separately inside a __tests__/ folder, or within the same folder with a .test.{js,ts,tsx} suffix.
All auto-generated files must be written either separately inside a __generated__/ folder, or within the same folder with a .generated.{js,ts,tsx} suffix.
Make sure to ignore these files in your TSLint/Prettier config.
Yes.
// Bad example
const maxThreshold = 25
// Good example
const maxThreshold = 25;It is recommended to include a trailing comma in multiline array/object statements. This will lead to cleaner git diffs.
// Bad example
const hero = {
firstName: 'Ada',
lastName: 'Lovelace',
birthYear: 1815,
superPower: 'computers'
};
// Good example
const hero = {
firstName: 'Ada',
lastName: 'Lovelace',
birthYear: 1815,
superPower: 'computers',
};Leaving the trailing comma on used to be a problem with legacy JavaScript, but ES6 no longer has that issue. Also, tools like Babel automatically removes the additional comma when compiling to older JavaScript.
The whole point of TypeScript is to be more specific than this. So when you can, try to replace any with a more specific type declaration, or use unknown to force explicit type-checking of external types.
When dealing with code that uses null (e.g. in HTML selectors or Redux), these should be kept isolated using selectors.
If a type error cannot be fixed for some reason, put a // @ts-ignore comment above the line with an explanation.
// @ts-ignore: doThing() api is changed on version 3.0 but the typings haven't been updated yet
const thing = doThing(one, two);Note that these should be treated as TODO items, since they're type errors that should be fixed next time there's a chance.
// Bad example
type responseObject = {}
// Good example
type ResponseObject = {}The type of a function's arguments must be declared, even if it's any.
// Bad example
function add(a, b) {
return a + b;
}
// Good example
function add(a: number, b: number) {
return a + b;
}// Bad example
interface checkoutButtonProps {}
// Good example
interface CheckoutButtonProps {}This convention is a leftover from early-day TS when people who mainly do C# started trying out TS, and is generally frowned upon nowadays, especially in frontend TS code.
We avoid prefixing interfaces with I specifically in the frontend.
// Bad example
interface ICheckoutButtonProps {}
// Good example
interface CheckoutButtonProps {}// Bad example
enum botStates {}
// Good example
enum BotStates {}Tools like Babel don't support this syntax. Use regular enums instead, or just use a plain old JS object.