Typescript
Everything from Clean Code concepts adapted for TypeScript
General
Prefer using an options object when the arguments' meaning isn't clear at the call site, for instance boolean flags, parameters of the same type that are easily mixed up, or optional parameters in the middle (Explanation: Clean Code concepts adapted for TypeScript)
const getSortedJobs = (orderBy: string, includeSoftDeleted: boolean, limit: number): Job[] => {};
getSortedJobs("createdAt", true, 20);
const getSortedJobs = (options: {
orderBy: string;
includeSoftDeleted: boolean;
limit: number;
}): Job[] => {};
getSortedJobs({
orderBy: "createdAt",
includeSoftDeleted: true,
limit: 20,
});
Positional parameters are fine when their meaning is obvious from the function name and argument values, even with more than two parameters, e.g. clamp(value, min, max) or addToCart(cart, product, quantity).
-
Use named exports only (Exception: Default exports are allowed only if technically required)
Reason: They are harder to locate and refactor. -
Use relative imports only for sibling or child files within a module (for anything else, use imports via @src)
This only applies to projects that define the@srcpath alias. Library packages compiled with plaintsccan't use it, becausetscdoesn't rewrite path aliases in its output, so they use relative imports, including for ancestor files. -
Prefer async/await over callbacks
-
Prefer for...of loops Supports all iterators, async/await, and control statements (See: Should one use for-of or forEach when iterating through an array?)
-
Use default arguments instead of short-circuiting or conditional logic
function createMicrobrewery(name) {
const breweryName = name || "Hipster Brew Co.";
// ...
}
function createMicrobrewery(name = "Hipster Brew Co.") {
// ...
}
3rd Party NPM packages
Further Reading / Sources
- Google TypeScript Style Guide
- Clean Code concepts adapted for TypeScript – GitHub by labs42io
- oida.dev | TypeScript, JavaScript, Rust
Naming Conventions
Enums
Use camelCase for the keys and values of your enums.
Example:
enum Direction {
north = "north",
northEast = "northEast",
east = "east",
southEast = "southEast",
south = "south",
southWest = "southWest",
west = "west",
northWest = "northWest",
}