Skip to main content
TypeScript Logo

TypeScript Style Guide

Introduction

TypeScript Style Guide and Agent Skill. A concise set of conventions and best practices for consistent, maintainable code.

Table of Contents

About Guide

What

Since "consistency is the key", TypeScript Style Guide strives to enforce the majority of rules using automated tools such as ESLint, TypeScript, Prettier, etc. However, certain design and architectural decisions must still be followed, as described in the conventions below.

Why

  • As project grow in size and complexity, maintaining code quality and ensuring consistent practices become increasingly challenging.
  • Defining and following a standard approach to writing TypeScript applications leads to a consistent codebase and faster development cycles.
  • No need to discuss code styles during code reviews.
  • Saves team time and energy.

Disclaimer

Like any code style guide, this one is opinionated, setting conventions (sometimes arbitrary) to govern our code.

You don't have to follow every convention exactly as written. Decide what works best for your product and team to maintain consistency in your codebase.

Requirements

This Style Guide requires:

The Style Guide assumes but is not limited to using:

Agent Skills

Agent Skills help coding agents apply, review, and explain the conventions in this guide. They complement TypeScript, linters, and formatters, which enforce automatable rules.

Install and choose a skill interactively:

npx skills add mkosir/typescript-style-guide

Or install a specific skill:

  • Complete guide: npx skills add mkosir/typescript-style-guide --skill typescript-style-guide
  • Types: npx skills add mkosir/typescript-style-guide --skill typescript-types
  • Discriminated Unions: npx skills add mkosir/typescript-style-guide --skill typescript-discriminated-unions
  • Functions: npx skills add mkosir/typescript-style-guide --skill typescript-functions
  • Variables: npx skills add mkosir/typescript-style-guide --skill typescript-variables
  • Naming: npx skills add mkosir/typescript-style-guide --skill typescript-naming
  • Source Organization: npx skills add mkosir/typescript-style-guide --skill typescript-source-organization
  • React: npx skills add mkosir/typescript-style-guide --skill typescript-react
  • Tests: npx skills add mkosir/typescript-style-guide --skill typescript-tests

The complete guide loads only the sections relevant to the task, not the entire guide, keeping the coding agent's context focused. Focused skills provide individual guide topics independently. Each option provides a shared reference for more consistent decisions across a codebase.

TLDR

  • Embrace const assertions for type safety and immutability.
  • Strive for data immutability using types like Readonly and ReadonlyArray.
  • Make the majority of object properties required (use optional properties sparingly).
  • Embrace discriminated unions.
  • Avoid type assertions in favor of proper type definitions.
  • Strive for functions to be pure, stateless, and have single responsibility.
  • Maintain consistent and readable naming conventions throughout the codebase.
  • Use named exports.
  • Organize code by feature and collocate related code as close as possible.

Types

When creating types, consider how they would best describe our code.
Being expressive and keeping types as narrow as possible offers several benefits to the codebase:

  • Increased Type Safety - Catch errors at compile time, as narrowed types provide more specific information about the shape and behavior of your data.
  • Improved Code Clarity - Reduces cognitive load by providing clearer boundaries and constraints on your data, making your code easier for other developers to understand.
  • Easier Refactoring - With narrower types, making changes to your code becomes less risky, allowing you to refactor with confidence.

Type Inference

As a rule of thumb, explicitly declare types only when it helps to narrow them.

Explicitly declare types when doing so helps to narrow them:

// ❌ Avoid
const employees = new Map(); // Inferred as wide type 'Map<any, any>'
employees.set('Lea', 17);
type UserRole = 'admin' | 'guest';
const [userRole, setUserRole] = useState('admin'); // Inferred as 'string', not the desired narrowed literal type

// ✅ Use explicit type declarations to narrow the types.
const employees = new Map<string, number>(); // Narrowed to 'Map<string, number>'
employees.set('Gabriel', 32);
type UserRole = 'admin' | 'guest';
const [userRole, setUserRole] = useState<UserRole>('admin'); // Explicit type 'UserRole'

Avoid explicitly declaring types when they can be inferred:

// ❌ Avoid
const userRole: string = 'admin'; // Inferred as wide type 'string'
const employees = new Map<string, number>([['Gabriel', 32]]); // Redundant type declaration
const [isActive, setIsActive] = useState<boolean>(false); // Redundant, inferred as 'boolean'

// ✅ Use type inference.
const USER_ROLE = 'admin'; // Inferred as narrowed string literal type 'admin'
const employees = new Map([['Gabriel', 32]]); // Inferred as 'Map<string, number>'
const [isActive, setIsActive] = useState(false); // Inferred as 'boolean'

Data Immutability

Immutability should be a key principle. Wherever possible, prevent unintended mutations with types like Readonly and ReadonlyArray.

  • Readonly types help prevent accidental mutations and bugs caused by unintended side effects. This protection exists during type checking and does not freeze values at runtime.
  • When performing data processing, always return new arrays, objects, or other reference-based data structures. To minimize cognitive load for future developers, strive to keep data objects flat and concise.
  • Use mutations sparingly, only in cases where they are truly necessary, such as when dealing with complex objects or optimizing for performance.
// ❌ Avoid data mutations
const removeFirstUser = (users: Array<User>) => {
if (users.length === 0) {
return users;
}
return users.splice(1);
};

// ✅ Use readonly type to prevent accidental mutations
const removeFirstUser = (users: ReadonlyArray<User>) => {
if (users.length === 0) {
return users;
}
return users.slice(1);
// Using arr.splice(1) errors - Function 'splice' does not exist on 'users'
};

Type-Safe Constants With Satisfies

The as const satisfies syntax combines narrow, readonly inference with type validation. It is useful when a constant should retain its exact values while conforming to a broader type.

Key benefits:

  • Readonly values with as const
    • Ensures the constant is treated as readonly.
    • Narrows the types of values to their literals, preventing accidental modifications.
  • Validation with satisfies
    • Ensures the object conforms to a broader type without widening its inferred type.
    • Helps catch type mismatches at compile time while preserving narrowed inferred types.

Array constants:

type UserRole = 'admin' | 'editor' | 'moderator' | 'viewer' | 'guest';

// ❌ Avoid constant of wide type
const DASHBOARD_ACCESS_ROLES: ReadonlyArray<UserRole> = ['admin', 'editor', 'moderator'];

// ❌ Avoid constant with incorrect values
const DASHBOARD_ACCESS_ROLES = ['admin', 'contributor', 'analyst'] as const;

// ✅ Use readonly constant of narrowed type
const DASHBOARD_ACCESS_ROLES = ['admin', 'editor', 'moderator'] as const satisfies ReadonlyArray<UserRole>;

Object constants:

type OrderStatus = {
pending: 'pending' | 'idle';
fulfilled: boolean;
error: string;
};

// ❌ Avoid mutable constant of wide type
const IDLE_ORDER: OrderStatus = {
pending: 'idle',
fulfilled: true,
error: 'Shipping Error',
};

// ❌ Avoid constant with incorrect values
const IDLE_ORDER = {
pending: 'done',
fulfilled: 'partially',
error: 116,
} as const;

// ✅ Use readonly constant of narrowed type
const IDLE_ORDER = {
pending: 'idle',
fulfilled: true,
error: 'Shipping Error',
} as const satisfies OrderStatus;

Template Literal Types

Embrace template literal types as they allow you to create precise and type-safe string constructs by interpolating values. They are a powerful alternative to using the wide string type, providing better type safety.

Template literal types constrain values known to TypeScript at compile time. They do not validate strings received at runtime.

Adopting template literal types brings several advantages:

  • Prevent errors caused by typos or invalid strings.
  • Provide better type safety and autocompletion support.
  • Improve code maintainability and readability.

Template literal types are useful in various practical scenarios, such as:

  • String Patterns - Use template literal types to enforce specific string patterns during type checking.

    // ❌ Avoid
    const appVersion = '2.6';
    // ✅ Use
    type Version = `v${number}.${number}.${number}`;
    const appVersion: Version = 'v2.6.1';
  • API Endpoints - Use template literal types to restrict values to valid API routes.

    // ❌ Avoid
    const userEndpoint = '/api/usersss'; // Type 'string' - Typo 'usersss': the route doesn't exist, leading to a runtime error.
    // ✅ Use
    type ApiRoute = 'users' | 'posts' | 'comments';
    type ApiEndpoint = `/api/${ApiRoute}`; // Type ApiEndpoint = "/api/users" | "/api/posts" | "/api/comments"
    const userEndpoint: ApiEndpoint = '/api/users';
  • Internationalization Keys - Avoid relying on raw strings for translation keys, which can lead to typos and missing translations. Use template literal types to constrain their structure.

    // ❌ Avoid
    const homeTitle = 'translation.homesss.title'; // Type 'string' - Typo 'homesss': the translation doesn't exist, leading to a runtime error.
    // ✅ Use
    type LocaleKeyPages = 'home' | 'about' | 'contact';
    type TranslationKey = `translation.${LocaleKeyPages}.${string}`; // Type TranslationKey = `translation.home.${string}` | `translation.about.${string}` | `translation.contact.${string}`
    const homeTitle: TranslationKey = 'translation.home.title';
  • CSS Utilities - Avoid raw strings for color values, which can lead to invalid or non-existent colors. Use template literal types to enforce known color names and require custom values to start with #.

    // ❌ Avoid
    const color = 'blue-450'; // Type 'string' - Color 'blue-450' doesn't exist, leading to a runtime error.
    // ✅ Use
    type BaseColor = 'blue' | 'red' | 'yellow' | 'gray';
    type Variant = 50 | 100 | 200 | 300 | 400;
    type Color = `${BaseColor}-${Variant}` | `#${string}`; // Type Color = "blue-50" | "blue-100" | "blue-200" ... | "red-50" | "red-100" ... | #${string}
    const iconColor: Color = 'blue-400';
    const customColor: Color = '#AD3128';
  • Database queries - Avoid using raw strings for table or column names, which can lead to typos. Use template literal types to define valid table and column combinations.

// ❌ Avoid
const query = 'SELECT name FROM usersss WHERE age > 30'; // Type 'string' - Typo 'usersss': table doesn't exist, leading to a runtime error.
// ✅ Use
type Table = 'users' | 'posts' | 'comments';
type Column<TTableName extends Table> =
TTableName extends 'users' ? 'id' | 'name' | 'age' :
TTableName extends 'posts' ? 'id' | 'title' | 'content' :
TTableName extends 'comments' ? 'id' | 'postId' | 'text' :
never;

type Query<TTableName extends Table> = `SELECT ${Column<TTableName>} FROM ${TTableName} WHERE ${string}`;
const userQuery: Query<'users'> = 'SELECT name FROM users WHERE age > 30'; // Accepted by Query<'users'>
const invalidQuery: Query<'users'> = 'SELECT title FROM users WHERE age > 30'; // Error: 'title' is not a column in 'users' table.

Type any & unknown

The any type must not be used because it bypasses type checking and allows unsafe operations and assignments. This can mask serious programming errors.

When dealing with ambiguous data, use unknown, which is the type-safe counterpart of any.
Anything can be assigned to unknown, but it must be narrowed before accessing its properties or assigning it to a more specific type.

// ❌ Avoid any
const foo: any = 'five';
const bar: number = foo; // no type error

// ✅ Use unknown
const foo: unknown = 5;
const bar: number = foo; // type error - Type 'unknown' is not assignable to type 'number'

// Narrow the type before dereferencing it using:
// Type guard
const isNumber = (num: unknown): num is number => {
return typeof num === 'number';
};
if (!isNumber(foo)) {
throw Error(`API provided a fault value for field 'foo':${foo}. Should be a number!`);
}
const bar: number = foo;

Type & Non-nullability Assertions

Type assertions user as User and non-nullability assertions user!.name are unsafe. Both only silence the TypeScript compiler and increase the risk of crashing the application at runtime.
They can only be used as an exception, such as a third-party library type mismatch, with a strong rationale for why they are introduced into the codebase.

type User = { id: string; username: string; avatar: string | null };
// ❌ Avoid type assertions
const user = { name: 'Nika' } as User;

// ❌ Avoid non-nullability assertions
const getUsername = (user: User | null) => user!.username; // Runtime error when user is null

Type Errors

When a TypeScript error cannot be mitigated, use @ts-expect-error as a last resort to suppress it.

This directive notifies the compiler when the suppressed error no longer exists, ensuring errors are revisited once they’re obsolete, unlike @ts-ignore, which can silently linger even after the error is resolved.

  • Always use @ts-expect-error with a clear description explaining why it is necessary.
  • Avoid @ts-ignore, as it does not track suppressed errors.
// ❌ Avoid @ts-ignore as it will do nothing if the following line is error-free.
// @ts-ignore
const newUser = createUser('Gabriel');

// ✅ Use @ts-expect-error with description.
// @ts-expect-error: This library function has incorrect type definitions - createUser accepts string as an argument.
const newUser = createUser('Gabriel');

Type Definition

TypeScript provides two options for defining types: type and interface. While these options have some functional differences, they are interchangeable in most cases. To maintain consistency, choose one and use it consistently.

Define all types using type alias
// ❌ Avoid interface definitions
interface UserRole = 'admin' | 'guest'; // Invalid - interfaces can't define type unions

interface UserInfo {
name: string;
role: 'admin' | 'guest';
}

// ✅ Use type definition
type UserRole = 'admin' | 'guest';

type UserInfo = {
name: string;
role: UserRole;
};

When performing declaration merging (e.g. extending third-party library types), use interface and disable the lint rule where necessary.

// types.ts
declare namespace NodeJS {
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
export interface ProcessEnv {
NODE_ENV: 'development' | 'production';
PORT: string;
CUSTOM_ENV_VAR: string;
}
}

// server.ts
app.listen(process.env.PORT, () => {...}

Array Types

Array types should be defined using generic syntax
// ❌ Avoid
const x: string[] = ['foo', 'bar'];
const y: readonly string[] = ['foo', 'bar'];

// ✅ Use
const x: Array<string> = ['foo', 'bar'];
const y: ReadonlyArray<string> = ['foo', 'bar'];

Type Imports and Exports

TypeScript allows specifying a type keyword on imports to indicate that the export exists only in the type system, not at runtime.

Type imports must always be separated:

  • Tree Shaking and Dead Code Elimination - import type is erased during compilation, leaving no runtime import for a bundler to analyze or remove.
  • Avoids Side Effects - Depending on compiler settings, a regular import used only as a type may remain in emitted JavaScript and run module side effects.
  • Code Clarity - Makes the difference between runtime and type-only imports explicit.
// ❌ Avoid using `import` for both runtime and type
import { MyClass } from 'some-library';

// Even if MyClass is only used as a type, a regular import can pull the module into the runtime bundle.

// ✅ Use `import type`
import type { MyClass } from 'some-library';

// This import is removed from the emitted JavaScript.

Services & Types Generation

Documentation becomes outdated the moment it's written, and worse than no documentation is wrong documentation. The same applies to types when describing the modules your app interacts with, such as APIs, messaging protocols, and databases.

For external services, such as REST, GraphQL, and MQ, it's crucial to generate types from their contracts, whether they use Swagger, schemas, or other sources (e.g. openapi-ts, graphql-config). Avoid manually declaring and maintaining types, as they can easily fall out of sync.

Generated types keep compile-time contracts in sync. They do not validate data received from external services at runtime.

As an exception, manually declare types only when no other options are available, such as when there is no documentation for the service, data cannot be fetched to retrieve a contract, or the database cannot be accessed to infer types.

Discriminated Unions

If there's only one TypeScript feature to choose from, embrace discriminated unions.

A discriminated union is a union of object types that share a property with distinct literal values. Checking that property narrows the value to the matching variant.

Use discriminated unions when variants are mutually exclusive and each variant requires different data. Keep properties optional when they may independently be absent, and use a literal union when only the value changes.

Prefer a shared literal discriminator when variants represent named states or modes and you control their shape. Use optional never properties only when property presence is itself the natural distinction and adding a discriminator would make the API less clear.

Discriminated unions are a powerful concept to model complex data structures and improve type safety, leading to clearer and less error-prone code.
You may encounter discriminated unions under different names, such as tagged unions or sum types, in languages such as C, Haskell, and Rust (in conjunction with pattern-matching).

Advantages of discriminated unions:

  • As mentioned in Required & Optional Object Properties, Function Arguments, and Props as Discriminated Type, discriminated unions replace optional properties that depend on a variant with required properties for that variant, reducing complexity.

  • Exhaustiveness Checking - The configured ESLint rule reports when a switch does not handle every variant of a discriminated union.

    type Circle = { kind: 'circle'; radius: number };
    type Square = { kind: 'square'; size: number };
    type Triangle = { kind: 'triangle'; base: number; height: number };

    // Create a discriminated union 'Shape', with the 'kind' property to discriminate the type of object.
    type Shape = Circle | Square | Triangle;

    const calculateArea = (shape: Shape) => {
    // ESLint reports that the switch is missing the 'triangle' case
    switch (shape.kind) {
    case 'circle':
    return Math.PI * shape.radius ** 2;
    case 'square':
    return shape.size ** 2;
    }
    };
  • Avoid code complexity introduced by multiple boolean flags that represent mutually exclusive states.

  • Clear code intent, as it becomes easier to read and understand by explicitly indicating the possible cases for a given type.

  • TypeScript can narrow down union types, ensuring code correctness at compile time.

  • Discriminated unions make refactoring and maintenance easier by providing a centralized definition of related types. When adding or modifying types within the union, the compiler reports any inconsistencies throughout the codebase.

  • IDEs can leverage discriminated unions to provide better autocompletion and type inference.

Practical Applications

Required & Optional Object Properties

Strive to have the majority of object properties required and use optional properties sparingly.

This approach reflects designing type-safe and maintainable code:

  • Clarity and Predictability - Required properties make it explicit which data is always expected. This reduces ambiguity for developers using or consuming the object, as they know exactly what must be present.
  • Type Safety - When properties are required, TypeScript can enforce their presence and catch missing properties during type checking.
  • Avoids Overuse of Optional Chaining - If too many properties are optional, it often leads to extensive use of optional chaining (?.) to handle potential undefined values. This clutters the code and obscures its intent.

Use optional properties when values may independently be absent. When property presence depends on the object's variant, use a discriminated union type.

// ❌ Avoid optional properties when their presence depends on the variant
type User = {
id?: number;
email?: string;
dashboardAccess?: boolean;
adminPermissions?: ReadonlyArray<string>;
subscriptionPlan?: 'free' | 'pro' | 'premium';
rewardsPoints?: number;
temporaryToken?: string;
};

// ✅ Use a discriminated union so each variant has only its required properties
type AdminUser = {
role: 'admin';
id: number;
email: string;
dashboardAccess: boolean;
adminPermissions: ReadonlyArray<string>;
};

type RegularUser = {
role: 'regular';
id: number;
email: string;
subscriptionPlan: 'free' | 'pro' | 'premium';
rewardsPoints: number;
};

type GuestUser = {
role: 'guest';
temporaryToken: string;
};

// Discriminated union type 'User' ensures clear intent with no optional properties
type User = AdminUser | RegularUser | GuestUser;

const regularUser: User = {
role: 'regular',
id: 212,
email: 'lea@user.com',
subscriptionPlan: 'pro',
rewardsPoints: 1500,
dashboardAccess: false, // Error: 'dashboardAccess' property does not exist
};

Application State

When application states require different data, model the state and its data together with a discriminated union. This prevents invalid combinations, such as loading while holding both data and an error.

// ❌ Boolean flags and optional properties allow invalid state combinations
type RequestState = {
isLoading: boolean;
data?: Products;
error?: string;
};

// ✅ Each state contains only the data valid for that state
type RequestState =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: Products }
| { status: 'error'; error: string };

Function Arguments

When a function accepts mutually exclusive variants that require different properties, use a discriminated union type. This decreases complexity in the function's API and ensures that only the required properties are passed for each use case.

// ❌ Avoid optional properties that allow invalid combinations in the function API
type NotificationParams = {
channel: 'email' | 'sms';
email?: string;
phoneNumber?: string;
subject?: string;
message: string;
};

// ✅ Use a discriminated union so each variant requires only its valid properties
type EmailNotificationParams = {
channel: 'email';
email: string;
subject: string;
message: string;
};

type SmsNotificationParams = {
channel: 'sms';
phoneNumber: string;
message: string;
};

type NotificationParams = EmailNotificationParams | SmsNotificationParams;

export const sendNotification = (params: NotificationParams) => {
switch (params.channel) {
case 'email':
return sendEmail(params.email, params.subject, params.message);
case 'sms':
return sendSms(params.phoneNumber, params.message);
}
};

React Props

Required & Optional Props

Strive to have the majority of props required and use optional props sparingly.

Especially when creating a new component for its first or single use case, the majority of props should be required. When the component starts covering more use cases, introduce optional props only for values that may genuinely be absent across those use cases.
There are potential exceptions where a component API needs to implement optional props from the start (e.g. shared components covering multiple use cases, UI design system components - button isDisabled etc.)

If a component or hook becomes too complex, it should probably be broken into smaller pieces.
An exaggerated example: implementing 10 React components with 5 required props each is better than implementing one "can do it all" component that accepts 50 optional props.

Props as Discriminated Type

When component variants require different props, use a discriminated union type. This approach reduces complexity in the component API and ensures that only the required props are passed for each variant.

// ❌ Avoid optional props that allow invalid combinations in the component API
type AvatarProps = {
variant: 'image' | 'initials';
src?: string;
alt?: string;
initials?: string;
};

// ✅ Use a discriminated union so each variant requires only its valid props
type ImageAvatarProps = {
variant: 'image';
src: string;
alt: string;
};

type InitialsAvatarProps = {
variant: 'initials';
initials: string;
};

type AvatarProps = ImageAvatarProps | InitialsAvatarProps;

export const Avatar = (props: AvatarProps) => {
switch (props.variant) {
case 'image':
return <img src={props.src} alt={props.alt} />;
case 'initials':
return <span>{props.initials}</span>;
}
};

Functions

Function conventions should be followed as much as possible (some derive from basic functional programming concepts):

General

Prefer functions that:

  • have a single responsibility.
  • make dependencies explicit through arguments.
  • return a value when they calculate or transform data.
  • avoid side effects when practical.

A stateless function does not retain data between calls. A deterministic function returns the same result for the same inputs. A pure function is deterministic and has no observable side effects, making it easier to understand, test, and reuse.

Not every function can be pure. Network requests, storage, logging, and UI updates require side effects. Keep these functions small and isolate side effects from pure business logic.

Single Object Arg

When a function accepts several related parameters, prefer a single object parameter. Named properties make call sites easier to understand and allow the function API to evolve without relying on argument order.

Keep positional parameters when their meaning and order are obvious, or when a conventional signature is clearer, such as isNumber(value) or a callback.

// ❌ Multiple arguments make this call difficult to understand
transformUserInput('client', false, 60, 120, null, true, 2000);

// ✅ An object makes each argument explicit
transformUserInput({
method: 'client',
isValidated: false,
minLines: 60,
maxLines: 120,
defaultInput: null,
shouldLog: true,
timeout: 2000,
});

Required & Optional Args

Strive to have the majority of arguments required and use optional arguments sparingly.
If the function becomes too complex, it probably should be broken into smaller pieces.
An exaggerated example: implementing 10 focused functions with 5 required arguments each is preferable to implementing one "do-it-all" function with 50 optional arguments.

When function arguments represent mutually exclusive cases, use discriminated unions.

Return Types

Requiring explicit return types improves safety, catches errors early, and helps with long-term maintainability. However, excessive strictness can slow development and add unnecessary redundancy.

As a rule of thumb, be explicit on the outside, implicit on the inside. For example, when building APIs or libraries, always type everything explicitly to avoid accidental breaking changes. For internal logic, let TypeScript infer its defaults, which will provide strong type safety without added verbosity.

Consider the advantages of explicitly defining the return type of a function:

  • Improves Readability: Clearly specifies what type of value the function returns, making the code easier to understand for those calling the function.
  • Avoids Misuse: Ensures that calling code does not accidentally attempt to use an undefined value when no return value is intended.
  • Surfaces Type Errors Early: Helps catch potential type errors during development, especially when code changes unintentionally alter the return type.
  • Simplifies Refactoring: Ensures that any variable assigned to the function's return value is of the correct type, making refactoring safer and more efficient.
  • Encourages Design Discussions: Similar to Test-Driven Development (TDD), explicitly defining function arguments and return types promotes discussions about a function's functionality and interface ahead of implementation.
  • Can Improve Compilation Performance: Explicit return types can reduce the work TypeScript needs to do, especially for complex inferred types.

As context matters, use explicit return types when they add clarity and safety.

Require explicit return types at module boundaries

Variables

Const Assertion

Strive to declare constants using the const assertion as const:

Constants are used to represent values that are not meant to change, ensuring reliability and consistency in a codebase. Const assertions preserve literal types and infer readonly properties.

  • Type Narrowing - Using as const ensures that literal values (e.g., numbers, strings) are treated as exact values instead of generalized types like number or string.
  • Readonly Properties - Objects and arrays get readonly properties, so TypeScript catches direct mutations.

Examples:

  • Objects

    // ❌ Avoid
    const FOO_LOCATION = { x: 50, y: 130 }; // Type { x: number; y: number; }
    FOO_LOCATION.x = 10;

    // ✅ Use
    const FOO_LOCATION = { x: 50, y: 130 } as const; // Type '{ readonly x: 50; readonly y: 130; }'
    FOO_LOCATION.x = 10; // Error
  • Arrays

    // ❌ Avoid
    const BAR_LOCATION = [50, 130]; // Type number[]
    BAR_LOCATION.push(10);

    // ✅ Use
    const BAR_LOCATION = [50, 130] as const; // Type 'readonly [50, 130]'
    BAR_LOCATION.push(10); // Error
  • Template Literals

    // ❌ Avoid
    const RATE_LIMIT = 25;
    const RATE_LIMIT_MESSAGE = `Max number of requests/min is ${RATE_LIMIT}.`; // Type string

    // ✅ Use
    const RATE_LIMIT = 25;
    const RATE_LIMIT_MESSAGE = `Max number of requests/min is ${RATE_LIMIT}.` as const; // Type 'Max number of requests/min is 25.'

Enums & Const Assertion

Enums are discouraged in the TypeScript ecosystem due to their runtime cost and quirks.
The TypeScript documentation outlines several pitfalls, and TypeScript 5.8 introduced the --erasableSyntaxOnly flag to disable runtime-generating features like enums altogether.

As a rule of thumb, prefer:

  • Literal types whenever possible.
  • Const assertion arrays when looping through values.
  • Const assertion objects when enumerating arbitrary values.

Examples:

  • Use literal types to avoid runtime objects and reduce bundle size.

    // ❌ Avoid using enums as they increase the bundle size
    enum UserRole {
    GUEST = 'guest',
    MODERATOR = 'moderator',
    ADMINISTRATOR = 'administrator',
    }

    // Transpiled JavaScript
    ('use strict');
    var UserRole;
    (function (UserRole) {
    UserRole['GUEST'] = 'guest';
    UserRole['MODERATOR'] = 'moderator';
    UserRole['ADMINISTRATOR'] = 'administrator';
    })(UserRole || (UserRole = {}));

    // ✅ Use literal types - Types are stripped during transpilation
    type UserRole = 'guest' | 'moderator' | 'administrator';

    const isGuest = (role: UserRole) => role === 'guest';
  • Use const assertion arrays when looping through values.

    // ❌ Avoid using enums
    enum USER_ROLES {
    guest = 'guest',
    moderator = 'moderator',
    administrator = 'administrator',
    }

    // ✅ Use const assertions arrays
    const USER_ROLES = ['guest', 'moderator', 'administrator'] as const;
    type UserRole = (typeof USER_ROLES)[number];

    const seedDatabase = () => {
    USER_ROLES.forEach((role) => {
    db.roles.insert(role);
    }
    }
    const insert = (role: UserRole) => {...

    const UsersRoleList = () => {
    return (
    <div>
    {USER_ROLES.map((role) => (
    <Item key={role} role={role} />
    ))}
    </div>
    );
    };
    const Item = ({ role }: { role: UserRole }) => {...
  • Use const assertion objects when enumerating arbitrary values.

    // ❌ Avoid using enums
    enum COLORS {
    primary = '#B33930',
    secondary = '#113A5C',
    brand = '#9C0E7D',
    }

    // ✅ Use const assertions objects
    const COLORS = {
    primary: '#B33930',
    secondary: '#113A5C',
    brand: '#9C0E7D',
    } as const;

    type Colors = typeof COLORS;
    type ColorKey = keyof Colors; // Type "primary" | "secondary" | "brand"
    type ColorValue = Colors[ColorKey]; // Type "#B33930" | "#113A5C" | "#9C0E7D"

    const setColor = (color: ColorValue) => {...

    setColor(COLORS.primary);
    setColor('#B33930');

Type Union & Boolean Flags

Embrace type unions, especially when type union options are mutually exclusive, instead multiple boolean flag variables.

Boolean flags have a tendency to accumulate over time, leading to confusing and error-prone code, since they hide the actual app state.

// ❌ Avoid introducing multiple boolean flag variables
const isPending, isProcessing, isConfirmed, isExpired;

// ✅ Use type union variable
type UserStatus = 'pending' | 'processing' | 'confirmed' | 'expired';
const userStatus: UserStatus;

Use a literal union when only the state value changes. When each state requires different data, use a discriminated union to represent the valid states explicitly.

Null & Undefined

With strictNullChecks, null and undefined have distinct types and meanings. Use them consistently based on what absence means in the application.
Strive to:

  • Use null when a value is explicitly empty, such as an assignment or function return value.
  • Use undefined when a value is missing or omitted, such as an optional field in a form, request payload, or database query (Prisma differentiation).

Naming

Strive to keep naming conventions consistent and readable, with important context provided, because another person will maintain the code you have written.

Named Export

Named exports must be used to ensure that all imports follow a uniform pattern

This keeps variable and function names consistent across the entire codebase. Named exports have the benefit of erroring when import statements try to import something that hasn't been declared.

Naming Conventions

While it's often hard to find the best name, aim to optimize code for consistency and future readers by following these conventions:

Variables

  • Locals
    Camel case
    products, productsFiltered

  • Booleans
    Prefixed with is, has etc.
    isDisabled, hasProduct

  • Constants
    Capitalized

    const FEATURED_PRODUCT_ID = '8f47d2a1-b13e-4d5a-a7d8-6ef1234';
  • Object & Array Constants

    Singular, capitalized with const assertion.

    const IDLE_ORDER = {
    pending: 'idle',
    fulfilled: true,
    error: 'Shipping Error',
    } as const;

    const DASHBOARD_ACCESS_ROLES = ['admin', 'editor', 'moderator'] as const;

    If a type exists, use Type-Safe Constants With Satisfies.

    // Type OrderStatus is predefined (e.g. generated from database schema, API)
    type OrderStatus = {
    pending: 'pending' | 'idle';
    fulfilled: boolean;
    error: string;
    };

    const IDLE_ORDER = {
    pending: 'idle',
    fulfilled: true,
    error: 'Shipping Error',
    } as const satisfies OrderStatus;

    // Type UserRole is predefined
    type UserRole = 'admin' | 'editor' | 'moderator' | 'viewer' | 'guest';

    const DASHBOARD_ACCESS_ROLES = ['admin', 'editor', 'moderator'] as const satisfies ReadonlyArray<UserRole>;

Functions

Camel case
filterProductsByType, formatCurrency

Types

Pascal case
OrderStatus, ProductItem

Generics

A generic type parameter must start with the capital letter T followed by a descriptive name TRequest, TFooBar.

Key reasons and benefits:

  • Complex types often involve generics, for which clear naming improves readability and maintainability.
  • Single-letter generics like T, K, and U are disallowed. The more parameters we introduce, the easier it is to mistake them.
  • Prefixing with T makes it immediately obvious that it's a generic type parameter, not a regular type.
  • A common scenario is when a generic parameter shadows an existing type because it has the same name, e.g. <Request extends Request>.
// ❌ Avoid naming generic parameters with one letter
const createPair = <T, K extends string>(first: T, second: K): [T, K] => {
return [first, second];
};
const pair = createPair(1, 'a');

// ✅ Use descriptive names starting with capital T
const createPair = <TFirst, TSecond extends string>(first: TFirst, second: TSecond): [TFirst, TSecond] => {
return [first, second];
};
const pair = createPair(1, 'a');

// ❌ Avoid naming generic parameters without a prefix - which 'Request' is which?
const handle = <Request extends Request>(req: Request): void => {...

// ✅ Prefix generic parameter with capital T
const handle = <TRequest extends Request>(req: TRequest): void => {...

Abbreviations & Acronyms

Treat acronyms as whole words, with capitalized first letter only.

// ❌ Avoid
const FAQList = ['qa-1', 'qa-2'];
const generateUserURL(params) => {...}

// ✅ Use
const FaqList = ['qa-1', 'qa-2'];
const generateUserUrl(params) => {...}

For readability, strive to avoid abbreviations, unless they are widely accepted and necessary.

// ❌ Avoid
const GetWin(params) => {...}

// ✅ Use
const GetWindow(params) => {...}

React Components

Pascal case
ProductItem, ProductsPage

Prop Types

React component name followed by the "Props" suffix
[ComponentName]Props - ProductItemProps, ProductsPageProps

Callback Props

Event handler (callback) props are prefixed with on* - e.g. onClick.
Event handler implementation functions are prefixed with handle* - e.g. handleClick.

// ❌ Avoid inconsistent callback prop naming
<Button click={actionClick} />
<MyComponent userSelectedOccurred={triggerUser} />

// ✅ Use prop prefix 'on*' and handler prefix 'handle*'
<Button onClick={handleClick} />
<MyComponent onUserSelected={handleUserSelected} />

React Hooks

Camel case, prefixed as 'use'
Symmetrical convention: [value, setValue] = useState()
// ❌ Avoid inconsistent useState hook naming
const [userName, setUser] = useState();
const [color, updateColor] = useState();
const [isActive, setActive] = useState();

// ✅ Use
const [name, setName] = useState();
const [color, setColor] = useState();
const [isActive, setIsActive] = useState();

A custom hook must always return an object.

// ❌ Avoid
const [products, errors] = useGetProducts();
const [fontSizes] = useTheme();

// ✅ Use
const { products, errors } = useGetProducts();
const { fontSizes } = useTheme();

Comments

Comments can quickly become outdated, leading to confusion rather than clarity.

Favor expressive code over comments by using meaningful names and clear logic. Comments should primarily explain "why," not "what" or "how."

Use comments when:

  • The context or reasoning isn't obvious from the code alone (e.g. config files, workarounds)
  • Referencing related issues, PRs, or planned improvements
// ❌ Avoid
// convert to minutes
const m = s * 60;
// avg users per minute
const myAvg = u / m;

// ✅ Use - Prefer expressive code by naming things what they are
const SECONDS_IN_MINUTE = 60;
const minutes = seconds * SECONDS_IN_MINUTE;
const averageUsersPerMinute = noOfUsers / minutes;

// ✅ Use - Reference planned improvements
// TODO: Move filtering to the backend once API v2 is released.
// Issue/PR - https://github.com/foo/repo/pulls/55124
const filteredUsers = frontendFiltering(selectedUsers);

// ✅ Use - Add context to explain why
// Use Fourier transformation to minimize information loss - https://github.com/dntj/jsfft#usage
const frequencies = signal.FFT();

TSDoc Comments

TSDoc standardizes TypeScript documentation comments so editors and documentation tools can interpret them consistently. This improves developer experience and supports generated API documentation.

Use TSDoc comments when documenting APIs, libraries, configurations, or reusable code.

/**
* Configuration options for the Web3 SDK.
*/
export type Web3Config = {
/** Ethereum network chain ID. */
chainId: number;

/**
* Gas price strategy for transactions:
* - `fast`: Higher fees, faster confirmation
* - `standard`: Balanced
* - `slow`: Lower fees, slower confirmation
*/
gasPriceStrategy: 'fast' | 'standard' | 'slow';

/** Maximum gas limit per transaction. */
maxGasLimit?: number;

/** Enables event listening for smart contract interactions. */
enableEventListener?: boolean;
};

Source Organization

Code Collocation

  • Every application or package in a monorepo has project files and folders organized and grouped by feature.
  • Collocate code as close as possible to where it's relevant.
  • Deep folder nesting should not represent an issue.

Imports

Import paths can be relative, starting with ./ or ../, or they can be absolute @common/utils.

To make import statements more readable and easier to understand:

  • Relative imports ./sortItems must be used when importing files within the same feature that are 'close' to each other. This also allows moving the feature around the codebase without changing these imports.
  • Absolute imports @common/utils must be used in all other cases.
  • All imports must be auto sorted by tooling e.g. prettier-plugin-sort-imports, eslint-plugin-import etc.
// ❌ Avoid
import { bar, foo } from '../../../../../../distant-folder';

// ✅ Use
import { locationApi } from '@api/locationApi';

import { foo } from '../../foo';
import { bar } from '../bar';
import { baz } from './baz';

Project Structure

Example frontend monorepo project where every application has files and folders grouped by feature:

apps/
├─ product-manager/
│ ├─ common/
│ │ ├─ components/
│ │ │ ├─ Button/
│ │ │ ├─ ProductTitle/
│ │ │ ├─ ...
│ │ │ └─ index.tsx
│ │ ├─ consts/
│ │ │ ├─ paths.ts
│ │ │ └─ ...
│ │ ├─ hooks/
│ │ └─ types/
│ ├─ modules/
│ │ ├─ HomePage/
│ │ ├─ ProductAddPage/
│ │ ├─ ProductPage/
│ │ ├─ ProductsPage/
│ │ │ ├─ api/
│ │ │ │ └─ useGetProducts/
│ │ │ ├─ components/
│ │ │ │ ├─ ProductItem/
│ │ │ │ ├─ ProductsStatistics/
│ │ │ │ └─ ...
│ │ │ ├─ utils/
│ │ │ │ └─ filterProductsByType/
│ │ │ └─ index.tsx
│ │ ├─ ...
│ │ └─ index.tsx
│ ├─ eslint.config.mjs
│ ├─ package.json
│ └─ tsconfig.json
├─ warehouse/
├─ admin-dashboard/
└─ ...
  • The modules folder is responsible for implementing each individual page and its custom features (components, hooks, utility functions etc.).
  • The common folder is responsible for implementations that are truly used across the application. Since it's a "global folder" it should be used sparingly.
    If the same component, e.g. common/components/ProductTitle, is used on more than one page, it shall be moved to the common folder.

When using a frontend framework with a file-system-based router (e.g. Next.js), the pages folder serves only as a router and is responsible for defining routes (no business logic implementation).

Example backend project structure with files and folders grouped by feature:

product-manager/
├─ dist/
├── database/
│ ├── migrations/
│ │ ├── 20220102063048_create_accounts.ts
│ │ └── ...
│ └── seeders/
│ ├── 20221116042655-feeds.ts
│ └── ...
├─ docker/
├─ logs/
├─ scripts/
├─ src/
│ ├─ common/
│ │ ├─ consts/
│ │ ├─ middleware/
│ │ ├─ types/
│ │ └─ ...
│ ├─ dao/
│ │ ├─ user/
│ │ └─ ...
│ ├─ modules/
│ │ ├── admin/
│ │ │ ├── account/
│ │ │ │ ├── account.model.ts
│ │ │ │ ├── account.controller.ts
│ │ │ │ ├── account.route.ts
│ │ │ │ ├── account.service.ts
│ │ │ │ ├── account.validation.ts
│ │ │ │ ├── account.test.ts
│ │ │ │ └── index.ts
│ │ │ └── ...
│ │ ├── general/
│ │ │ ├── general.model.ts
│ │ │ ├── general.controller.ts
│ │ │ ├── general.route.ts
│ │ │ ├── general.service.ts
│ │ │ ├── general.validation.ts
│ │ │ ├── general.test.ts
│ │ │ └── index.ts
│ │ ├─ ...
│ │ └─ index.tsx
│ └─ ...
├─ ...
├─ eslint.config.mjs
├─ package.json
└─ tsconfig.json

Appendix - React

Since React components and hooks are also functions, the respective function conventions apply.

Props To State

In general, avoid using props as initial state because the state will not update when the props change. This can lead to bugs that are hard to track, unintended side effects, and difficulty testing.
When there is truly a use case for using a prop as initial state, the prop must be prefixed with initial (e.g. initialProduct, initialSort etc.)

// ❌ Avoid using props to state
type FooProps = {
productName: string;
userId: string;
};

export const Foo = ({ productName, userId }: FooProps) => {
const [productName, setProductName] = useState(productName);
...

// ✅ Use prop prefix `initial` when there is a rationale for it
type FooProps = {
initialProductName: string;
userId: string;
};

export const Foo = ({ initialProductName, userId }: FooProps) => {
const [productName, setProductName] = useState(initialProductName);
...

Props Type

// ❌ Avoid using React.FC type
type FooProps = {
name: string;
score: number;
};

export const Foo: React.FC<FooProps> = ({ name, score }) => {

// ✅ Use props argument with type
type FooProps = {
name: string;
score: number;
};

export const Foo = ({ name, score }: FooProps) => {...

Component Types

Container

  • All container components have the suffix "Container" or "Page" [ComponentName]Container|Page. Use the "Page" suffix to indicate that a component is an actual web page.
  • Each feature has a container component (AddUserContainer.tsx, EditProductContainer.tsx, ProductsPage.tsx etc.)
  • Includes business logic.
  • API integration.
  • Structure:
    ProductsPage/
    ├─ api/
    │ └─ useGetProducts/
    ├─ components/
    │ └─ ProductItem/
    ├─ utils/
    │ └─ filterProductsByType/
    └─ index.tsx

UI - Feature

  • Representational components that are designed to fulfill feature requirements.
  • Nested inside container component folder.
  • Should follow function conventions as much as possible.
  • No API integration.
  • Structure:
    ProductItem/
    ├─ index.tsx
    ├─ ProductItem.stories.tsx
    └─ ProductItem.test.tsx

UI - Design system

  • Globally reusable or shared components used throughout the whole codebase.
  • Structure:
    Button/
    ├─ index.tsx
    ├─ Button.stories.tsx
    └─ Button.test.tsx

Store & Pass Data

  • Pass only the necessary props to child components rather than passing the entire object.

  • Utilize storing state in the URL, especially for filtering, sorting etc.

  • Don't sync URL state with local state.

  • Consider passing data simply through props, using the URL, or composing children. Use global state (Zustand, Context) as a last resort.

  • Use React compound components when components should belong and work together: menu, accordion, navigation, tabs, list, etc.
    Always export compound components as:

    // PriceList.tsx
    const PriceListRoot = ({ children }) => <ul>{children}</ul>;
    const PriceListItem = ({ title, amount }) => <li>Name: {name} - Amount: {amount}<li/>;

    // ❌
    export const PriceList = {
    Container: PriceListRoot,
    Item: PriceListItem,
    };
    // ❌
    PriceList.Item = Item;
    export default PriceList;

    // ✅
    export const PriceList = PriceListRoot as typeof PriceListRoot & {
    Item: typeof PriceListItem;
    };
    PriceList.Item = PriceListItem;

    // App.tsx
    import { PriceList } from "./PriceList";

    <PriceList>
    <PriceList.Item title="Item 1" amount={8} />
    <PriceList.Item title="Item 2" amount={12} />
    </PriceList>;
  • UI components should show derived state and send events, nothing more (no business logic).

  • As in many programming languages, function arguments can be passed to the next function and on to the next etc.
    React components are no different, so prop drilling should not become an issue.
    If prop drilling truly becomes an issue as the app scales, try refactoring render methods or local state in parent components, or use composition.

  • Data fetching is only allowed in container components.

  • The use of a server-state library is encouraged (TanStack Query, Apollo Client etc.).

  • Use of client-state library for global state is discouraged.
    Reconsider whether something should be truly global across the application, e.g. themeMode or Permissions, or whether it can be put in server state (e.g. user settings from the /me endpoint). If global state is still truly needed, use Zustand or Context.

Appendix - Tests

What & How To Test

Automated tests help us write better code, make refactoring easier, and catch bugs earlier in the process.
Consider the trade-offs of what and how to test to gain confidence that the application is working as intended, while ensuring that writing and maintaining tests doesn't slow the team down.

✅ Do:

  • Keep tests short, explicit, and pleasant to work with. A test's intent should be immediately visible.
  • Strive to follow the AAA pattern to maintain clean, organized, and understandable unit tests.
    • Arrange - Setup preconditions or the initial state necessary for the test case. Create necessary objects and define input values.
    • Act - Perform the action you want to unit test (invoke a method, triggering an event etc.). Strive for minimal number of actions.
    • Assert - Validate the outcome against expectations. Strive for minimal number of asserts.
      The rule "unit tests should fail for exactly one reason" doesn't always need to apply, but tests with many assertions can indicate a code smell.
  • As mentioned in function conventions, try to keep functions pure and impure ones small and focused.
    This makes them easy to test by passing arguments and observing return values, since we will rarely need to mock dependencies.
  • Strive to write tests based on how a user interacts with your app, meaning test business logic.
    E.g. for a specific user role or permission, given some input, we receive the expected output from the process.
  • Make tests as isolated as possible so they don't depend on execution order and can run independently with their own local storage, session storage, data, cookies etc. Test isolation speeds up the test run, improves reproducibility, makes debugging easier and prevents cascading test failures.
  • Tests should be resilient to changes.
    • Black box testing - Always test only publicly exposed behavior. Don't write fragile tests based on how the implementation works internally.
    • Query HTML elements based on attributes that are unlikely to change. Order of priority must be followed as specified in Testing Library - role, label, placeholder, text contents, display value, alt text, title, test ID.
    • If testing with a database, make sure you control the data. If tests are run against a staging environment, make sure it doesn't change.

❌ Don't:

  • Don't test implementation details. When refactoring code, tests shouldn't change.
  • Don't re-test the library/framework.
  • Don't mandate 100% code coverage for applications.
  • Don't test third-party dependencies. Only test what your team controls (package, API, microservice etc.). Don't test external site links, third-party servers, packages etc.
  • Don't test just to test. Every test should provide meaningful confidence.

Test Description

All test descriptions must follow the naming convention it('should ... when ...').

// ❌ Avoid
it('accepts ISO date format where date is parsed and formatted as YYYY-MM');
it('after title is confirmed user description is rendered');

// ✅ Name test description as it('should ... when ...')
it('should return parsed date as YYYY-MM when input is in ISO date format');
it('should render user description when title is confirmed');

Snapshot

Snapshot tests are discouraged to avoid fragility, which leads to a "just update it" mindset to make all tests pass.
Exceptions can be made with strong rationale when the snapshot is short and clearly communicates what's being tested (e.g., critical design system library elements that shouldn't deviate).