TypeScript has evolved significantly. What was best practice two years ago may not be optimal today. As CTO of Softechinfra, I've established TypeScript standards across all our projects. Here are current best practices.
Type System Best Practices
1. Use Strict Mode
Enable all strict checks:
{
"compilerOptions": {
"strict": true,
"noUncheckedIndexedAccess": true,
"noImplicitReturns": true
}
}2. Prefer Type Inference
Let TypeScript work for you:
// Unnecessary
const name: string = "John"// Better - inference works
const name = "John"
// Explicit when needed
function getUser(): User {
// ...
}
3. Use Discriminated Unions
For complex states:
type State =
| { status: 'loading' }
| { status: 'success'; data: Data }
| { status: 'error'; error: Error }4. Avoid any
Use unknown for truly unknown types:
// Avoid
function handle(input: any) {}// Better
function handle(input: unknown) {
if (typeof input === 'string') {
// TypeScript knows it's a string
}
}
Modern Patterns
Const Assertions
Preserve literal types:
const config = {
endpoint: '/api',
timeout: 5000
} as const// Type is { readonly endpoint: '/api'; readonly timeout: 5000 }
Satisfies Operator
Type checking without widening:
type Colors = Recordconst palette = {
red: [255, 0, 0],
green: [0, 255, 0],
} satisfies Colors
// palette.red is [number, number, number], not number[]
Template Literal Types
For string manipulation:
type EventName = on${Capitalize}
type ClickHandler = EventName<'click'> // 'onClick' Utility Types
Essential Utilities
// Pick specific properties
type UserPreview = Pick// Omit properties
type UserWithoutPassword = Omit
// Make all optional
type PartialUser = Partial
// Make all required
type RequiredUser = Required
// Read-only version
type ImmutableUser = Readonly
Custom Utilities
Build reusable type utilities:
type NonNullableFields = {
[K in keyof T]: NonNullable
} Project Organization
File Structure
Type Declarations
src/
types/
index.ts # Shared types
api.ts # API types
components/
Button/
Button.tsx
Button.types.ts # Component-specificCommon Mistakes
For more on React development, see our React Server Components Guide.
Need Type-Safe Development?
Our development team writes clean, maintainable TypeScript code. From Next.js to Node.js, we build applications with confidence.
Get Free Consultation →