TypeScript Configuration
Comprehensive guide to TypeScript configuration in the project template.
Configuration Files
Development Configuration (tsconfig.json
)
json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"sourceMap": true
},
"include": ["src/**/*", "__tests__/**/*"],
"exclude": ["node_modules", "dist"]
}
Production Configuration (tsconfig.build.json
)
json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"noEmit": false,
"outDir": "dist",
"declaration": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["__tests__/**/*", "node_modules", "dist"]
}
Compiler Options Explained
Target & Module
- target: "ES2022" - Modern JavaScript features for Node.js 18+
- module: "ESNext" - Latest module syntax for optimal tree-shaking
- moduleResolution: "bundler" - Modern module resolution
Strict Type Checking
- strict: true - Enables all strict type checking options
- noImplicitAny: true - Error on expressions with implied 'any' type
- strictNullChecks: true - Enable strict null checks
- strictFunctionTypes: true - Enable strict checking of function types
Module Resolution
- esModuleInterop: true - Enables emit interoperability between CommonJS and ES Modules
- allowSyntheticDefaultImports: true - Allow default imports from modules with no default export
- forceConsistentCasingInFileNames: true - Disallow inconsistently-cased references
Output Options
- declaration: true - Generate .d.ts files
- sourceMap: true - Generate source map files
- outDir: "dist" - Redirect output structure to the directory
Path Mapping (Optional)
For larger projects, you can configure path mapping:
json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@utils/*": ["src/utils/*"],
"@types/*": ["src/types/*"]
}
}
}
Usage:
typescript
// Instead of: import { utils } from '../../../utils/helpers'
import { utils } from '@utils/helpers';
Type Definitions
Custom Types
Create src/types/index.ts
for project-specific types:
typescript
// Global type definitions
export interface AppConfig {
name: string;
version: string;
environment: 'development' | 'production' | 'test';
}
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
export interface Logger {
level: LogLevel;
log(level: LogLevel, message: string): void;
}
Ambient Declarations
For third-party modules without types, create src/types/global.d.ts
:
typescript
// Declare modules without type definitions
declare module 'some-untyped-module' {
export function someFunction(param: string): number;
}
// Extend global namespace if needed
declare global {
namespace NodeJS {
interface ProcessEnv {
NODE_ENV: 'development' | 'production' | 'test';
PORT?: string;
}
}
}
Strict Configuration Benefits
Type Safety
typescript
// ✅ Good - explicit types
function processUser(user: { name: string; age: number }): string {
return `${user.name} is ${user.age} years old`;
}
// ❌ Bad - implicit any (caught by strict mode)
function processUser(user) {
return `${user.name} is ${user.age} years old`;
}
Null Safety
typescript
// ✅ Good - null checks
function getName(user: { name?: string }): string {
return user.name ?? 'Unknown';
}
// ❌ Bad - potential null reference (caught by strictNullChecks)
function getName(user: { name?: string }): string {
return user.name.toUpperCase(); // Error: Object is possibly 'undefined'
}
Advanced Configuration
Project References
For monorepos or complex projects:
json
{
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/utils" }
]
}
Incremental Compilation
json
{
"compilerOptions": {
"incremental": true,
"tsBuildInfoFile": ".tsbuildinfo"
}
}
Custom Transformers
json
{
"compilerOptions": {
"plugins": [
{
"name": "typescript-transform-paths"
}
]
}
}
IDE Integration
VS Code Settings
.vscode/settings.json
:
json
{
"typescript.preferences.importModuleSpecifier": "relative",
"typescript.suggest.autoImports": true,
"typescript.updateImportsOnFileMove.enabled": "always",
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
}
IntelliSense Configuration
json
{
"compilerOptions": {
"declaration": true,
"declarationMap": true
}
}
Performance Optimization
Faster Compilation
json
{
"compilerOptions": {
"skipLibCheck": true,
"incremental": true
},
"exclude": [
"node_modules",
"**/*.test.ts",
"**/*.spec.ts"
]
}
Memory Usage
json
{
"compilerOptions": {
"preserveWatchOutput": true
},
"watchOptions": {
"excludeDirectories": ["**/node_modules", "_build"]
}
}
Troubleshooting
Common Issues
Module Resolution Errors
bash
# Debug module resolution
npx tsc --traceResolution
# Check configuration
npx tsc --showConfig
Type Errors
bash
# Verbose type checking
npx tsc --noEmit --listFiles
# Skip lib checking for faster builds
npx tsc --skipLibCheck
Performance Issues
bash
# Analyze compilation performance
npx tsc --diagnostics
# Use incremental compilation
npx tsc --incremental
Migration Guide
From JavaScript
- Rename
.js
files to.ts
- Add type annotations gradually
- Enable strict mode incrementally
- Fix type errors systematically
Upgrading TypeScript
- Update TypeScript version
- Review breaking changes
- Update configuration options
- Test compilation and runtime
Best Practices
Configuration Management
- Use extends for shared configurations
- Separate dev/prod configurations
- Document custom options in comments
- Version control all configuration files
Type Definitions
- Explicit return types for public APIs
- Interface over type for object shapes
- Utility types for transformations
- Generic constraints for flexibility
Project Organization
- Consistent file naming conventions
- Logical directory structure
- Clear module boundaries
- Minimal circular dependencies