Skip to content

Instantly share code, notes, and snippets.

@eonist
Created June 7, 2025 12:07
Show Gist options
  • Save eonist/d09bd4a47ff14b6080aef5d0c83537b7 to your computer and use it in GitHub Desktop.
Save eonist/d09bd4a47ff14b6080aef5d0c83537b7 to your computer and use it in GitHub Desktop.
typescript_best_practice

Type System and Safety

Use proper primitive types Always use lowercase primitive types (number, string, boolean, symbol) instead of their capitalized boxed object counterparts (Number, String, Boolean, Symbol, Object)[1]. Use object instead of Object for non-primitive types[1].

Avoid any, prefer unknown The any type defeats TypeScript's purpose by bypassing type checking[4][6][7]. When the type is uncertain, use unknown instead, which requires type-checking before operations can be performed[4][7].

Enable strict typing Set "strict": true in your tsconfig.json and consider additional options like "noImplicitAny" and "strictNullChecks"[4]. This reveals hidden bugs and makes your codebase more reliable[4].

Use string literal types Instead of declaring variables as generic string types, define the specific set of possible values: type Status = "active" | "inactive" | "pending"[4][6]. This prevents bugs during compile time rather than runtime[6].

Interfaces and Types

Choose interfaces vs types appropriately Use interfaces when defining objects that might benefit from inheritance or future extension[4]. Use types for unions or complex data structures where extension isn't needed[4].

Leverage utility types TypeScript provides built-in utility types like Partial, Pick, Omit, and Readonly that make code more concise and avoid repetitive definitions[4][6].

Use readonly for immutability Add readonly to properties that shouldn't change after initialization to prevent accidental mutation and clarify data immutability[4].

Naming Conventions

Follow consistent naming patterns[2]:

  • Use PascalCase for type names and enum values
  • Use camelCase for function names, property names, and local variables
  • Don't use "I" as a prefix for interface names
  • Use "_" as a prefix for private properties
  • Use whole words when possible, avoiding unclear abbreviations

Choose meaningful names Variable and function names should clearly communicate their purpose[6]. Avoid cryptic names like x1 or overly verbose names like incrementorForMainLoopFromTenToTwenty[6].

Code Style and Structure

Function declarations Always explicitly define return types for functions, especially those longer than one line[2][4]. This makes code more predictable and helps TypeScript catch errors if function behavior changes[4].

Variable declarations Never use var; instead use const where possible and let otherwise[2][5][6]. Use single declarations per variable statement (let x = 1; let y = 2; instead of let x = 1, y = 2;)[2][5].

Code formatting[2][3][5]:

  • Use 2 spaces for indentation, not tabs
  • Use semicolons
  • Open curly braces on the same line as the statement
  • Always wrap statement bodies in curly braces
  • Use arrow functions over anonymous function expressions
  • No surrounding whitespace in parenthesized constructs

Error Handling and Safety

Handle null and undefined safely Use optional chaining (?.) and nullish coalescing (??) operators to handle these cases gracefully: const userName = user?.profile?.name ?? "Guest"[4].

Implement exhaustive checking Use the never type in switch statements to ensure all union type cases are handled[4]. This prevents unhandled cases when new options are added to union types[4].

Use proper access modifiers Utilize public, private, and protected access modifiers to restrict access to class members and prevent inadvertent exposure of sensitive data[7].

Security Considerations

Validate user input Always validate and sanitize user input, especially when interacting with databases, file systems, or third-party services[7].

Avoid dynamic code execution Never use eval() or other dynamic code execution methods, as they can introduce security vulnerabilities[7].

Use strict equality Always use === and !== instead of == and != to avoid type coercion issues[6].

Manage dependencies carefully Only use well-maintained and trusted libraries, regularly update dependencies, and check for known vulnerabilities using tools like npm audit[7].

[1] https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html [2] https://www.itwinjs.org/learning/guidelines/typescript-coding-guidelines/ [3] https://gist.github.com/anichitiandreea/e1d466022d772ea22db56399a7af576b [4] https://dev.to/yugjadvani/how-to-write-better-typescript-code-best-practices-for-clean-effective-and-scalable-code-38d2 [5] https://github.com/microsoft/TypeScript/wiki/Coding-guidelines [6] https://github.com/andredesousa/typescript-best-practices [7] https://www.aptori.com/blog/secure-coding-in-typescript-best-practices-to-build-secure-applications [8] https://docs.aws.amazon.com/prescriptive-guidance/latest/best-practices-cdk-typescript-iac/typescript-best-practices.html [9] https://developer.enonic.com/docs/typescript-starter [10] https://google.github.io/styleguide/tsguide.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment