TypeScript
Our standards and best practices for using TypeScript.
We use TypeScript across our entire codebase to ensure type safety, improve developer experience, and catch errors early. This document outlines our standards and best practices for writing high-quality TypeScript code.
Strict Configuration
We leverage TypeScript's strictest compiler options to enforce a high level of type safety. Our tsconfig.json is configured with flags like:
"strict": true"noImplicitAny": true"strictNullChecks": true"forceConsistentCasingInFileNames": true
This helps us write more robust code and prevent common bugs.
Advanced Types and Generics
We encourage the use of advanced TypeScript features to create flexible and reusable code.
- Generics: Use generics to create components, functions, and classes that can work with a variety of types while maintaining type safety.
- Utility Types: Leverage built-in utility types like
Partial,Required,Pick, andOmitto manipulate existing types without creating new ones from scratch. - Conditional Types: For more complex scenarios, use conditional types to create types that change based on certain conditions.
Type Inference
While explicit type annotations are often useful, we prefer to let TypeScript infer types whenever it's clear and doesn't reduce readability. This can lead to cleaner, more concise code.
For example, instead of:
let name: string = 'AInstein';Prefer:
let name = 'AInstein'; // TypeScript correctly infers the type as stringInterfaces and Types
- Use
interfacefor object shapes: When defining the shape of an object or a class, prefer using aninterface. - Use
typefor primitives, unions, and tuples: For defining aliases for primitive types, union types, or tuples, use atypealias.
Type Safety in Practice
- Zod for Validation: For validating data at runtime (e.g., from API responses or user input), we use Zod. This allows us to bridge the gap between runtime data and our static types.
- Type Guards: Use type guards to narrow down the type of a variable within a conditional block.
By adhering to these standards, we can build a more robust, maintainable, and scalable application.