Skip to main content

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)

Bad
const getSortedJobs = (orderBy: string, includeSoftDeleted: boolean, limit: number): Job[] => {};

getSortedJobs("createdAt", true, 20);
Good
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 @src path alias. Library packages compiled with plain tsc can't use it, because tsc doesn'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

Bad
function createMicrobrewery(name) {
const breweryName = name || "Hipster Brew Co.";
// ...
}
Good
function createMicrobrewery(name = "Hipster Brew Co.") {
// ...
}

3rd Party NPM packages​

See Libraries and Techniques

Further Reading / Sources​

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",
}