Skip to content

NeaByteLab/TypeScript-Starter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

9 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”§ TypeScript Starter

Node.js TypeScript License

TypeScript Starter - A starter template with TypeScript rules, tooling, and configuration for Node.js projects.


🎯 Strict Coding Rules (Enforced)

TypeScript Rules

// βœ… ENFORCED: Strict mode with comprehensive type checking
// βœ… ENFORCED: No implicit any types
// βœ… ENFORCED: No unused variables or parameters
// βœ… ENFORCED: All code paths must return
// βœ… ENFORCED: Explicit type annotations required
// βœ… ENFORCED: No unreachable code
// βœ… ENFORCED: Exact optional property types
// βœ… ENFORCED: No unchecked indexed access

// ❌ This will fail:
function badFunction(input) {  // implicit any
  if (condition) return value  // not all paths return
  const unused = "never used"  // unused variable
}

// βœ… This passes:
function goodFunction: (input: string) => string = (input: string): string => {
  if (condition) {
    return value
  }
  return defaultValue
}

Code Style Rules

// βœ… ENFORCED: Single quotes, no semicolons
// βœ… ENFORCED: 2-space indentation
// βœ… ENFORCED: No trailing commas
// βœ… ENFORCED: Required curly braces
// βœ… ENFORCED: Spaces inside object braces
// βœ… ENFORCED: No spaces inside array brackets
// βœ… ENFORCED: Consistent naming conventions

// ❌ This will fail:
const obj = {a: 1, b: 2,};   // trailing comma
const arr = [ 1, 2, 3 ];     // spaces in array
if(condition) return value;  // no curly braces, semicolon

// βœ… This passes:
const obj = { a: 1, b: 2 }
const arr = [1, 2, 3]
if (condition) {
  return value
}

Best Practices Rules

// βœ… ENFORCED: Prefer const over let/var
// βœ… ENFORCED: Arrow functions for callbacks
// βœ… ENFORCED: Template literals over concatenation
// βœ… ENFORCED: Object destructuring where applicable
// βœ… ENFORCED: No inline comments
// βœ… ENFORCED: Cognitive complexity ≀ 15
// βœ… ENFORCED: No duplicate code
// βœ… ENFORCED: Prefer immediate returns

// ❌ This will fail:
var oldWay = "string" + variable;  // var, concatenation
function callback() { return value; }  // function instead of arrow
// inline comment  // inline comment

// βœ… This passes:
const newWay = `string ${variable}`
const callback = () => value
// Block comment for complex logic

Quality Rules

// βœ… ENFORCED: No duplicate strings
// βœ… ENFORCED: No identical functions
// βœ… ENFORCED: No redundant boolean expressions
// βœ… ENFORCED: Prefer immediate returns
// βœ… ENFORCED: No one-iteration loops
// βœ… ENFORCED: No unused variables
// βœ… ENFORCED: No unreachable code

// ❌ This will fail:
const message = "Hello"
const greeting = "Hello"   // duplicate string

if (condition === true) {  // redundant boolean
  return value
}

// βœ… This passes:
const MESSAGES = {
  GREETING: "Hello"
} as const

if (condition) {
  return value
}

πŸš€ Quick Start

Installation

# Clone and start coding
git clone https://github.com/NeaByteLab/TypeScript-Starter.git my-project
cd my-project
npm install
npm run dev

Development Commands

# Development
npm run dev                # TypeScript watch mode
npm run build              # Build for production
npm run clean              # Clean build directory

# Code Quality
npm run lint               # ESLint with strict rules
npm run lint:fix           # Auto-fix ESLint violations
npm run format             # Prettier formatting
npm run type-check         # TypeScript type checking

# Testing
npm run test               # Run tests with Jest
npm run test:watch         # Watch mode for TDD
npm run test:coverage      # Run tests with coverage

# Documentation
npm run docs               # Generate TypeDoc documentation

# Quality Assurance
npm run check-all          # Run all checks

πŸ“ Project Structure

TypeScript-Starter/
β”œβ”€β”€ src/                      # Source code
β”‚   β”œβ”€β”€ types/                # Type definitions
β”‚   β”‚   └── index.ts          # Common types: ConfigOptions, Result<T>, EventHandler, etc.
β”‚   β”œβ”€β”€ utils/                # Utility functions
β”‚   β”‚   └── index.ts          # Helper functions: isNotEmpty, createSuccessResult, etc.
β”‚   └── index.ts              # Main entry point - exports all public APIs
β”œβ”€β”€ tests/                    # Test files
β”‚   β”œβ”€β”€ setup.ts              # Jest test setup and global configurations
β”‚   └── example.test.ts       # Test suite for all functions
β”œβ”€β”€ examples/                 # Example usage
β”‚   └── basic-usage.ts        # Usage examples with async support
β”œβ”€β”€ dist/                     # Build output (ESM + type definitions)
β”œβ”€β”€ docs/                     # Auto-generated TypeDoc documentation
β”œβ”€β”€ coverage/                 # Test coverage reports (HTML + LCOV)
└── Configuration Files       # Strict rules enforced
    β”œβ”€β”€ tsconfig.json         # TypeScript configuration (all strict options enabled)
    β”œβ”€β”€ eslint.config.js      # ESLint configuration (200+ rules)
    β”œβ”€β”€ jest.config.js        # Jest testing configuration with TypeScript
    └── package.json          # Dependencies and scripts

πŸ“¦ Core API Reference

Type Definitions

// Configuration options interface
export interface ConfigOptions {
  readonly debug: boolean
  readonly timeout: number
  readonly retries: number
}

// Result type for operations (success/error handling)
export type Result<T> = {
  readonly success: boolean
  readonly data?: T
  readonly error?: string
}

// Event handler type
export type EventHandler<T = unknown> = (event: T) => void

// Async operation type
export type AsyncOperation<T> = () => Promise<T>

// Validation function type
export type Validator<T> = (value: T) => boolean

Utility Functions

// String validation
export const isNotEmpty: (value: string) => boolean

// Result constructors
export const createSuccessResult: <T>(data: T) => Result<T>
export const createErrorResult: <T>(error: string) => Result<T>

// Async utilities
export const delay: (ms: number) => Promise<void>

Main Exports

// Example function (demonstrates strict typing)
export const exampleFunction: (input: string) => string

// Example class (demonstrates OOP with strict rules)
export class ExampleClass {
  constructor(value: string)
  public getValue(): string
  public setValue(newValue: string): void
}

Usage Examples

import {
  exampleFunction,
  ExampleClass,
  isNotEmpty,
  createSuccessResult,
  createErrorResult,
  delay,
  type ConfigOptions,
  type Result
} from 'typescript-starter'

// Function usage
const result = exampleFunction('hello world')
console.log(result) // "HELLO WORLD"

// Class usage
const instance = new ExampleClass('test value')
console.log(instance.getValue()) // "TEST VALUE"

// Utility usage
console.log(isNotEmpty('valid')) // true
console.log(isNotEmpty('')) // false

const success = createSuccessResult({ message: 'OK' })
const error = createErrorResult<string>('Failed')

// Async usage
await delay(1000)
console.log('Delayed execution')

πŸ“Š Code Quality Metrics

Cognitive Complexity Limit: 15

// ❌ Too complex (will fail)
function complexFunction(input: string): string {
  if (condition1) {
    if (condition2) {
      if (condition3) {
        if (condition4) {
          if (condition5) {
            return "too complex"
          }
        }
      }
    }
  }
  return "default"
}

// βœ… Simple and clear (passes)
function simpleFunction(input: string): string {
  if (!condition1) return "default"
  if (!condition2) return "default"
  if (!condition3) return "default"
  return "result"
}

Type Safety

// ❌ These will fail compilation
function badFunction(input) {           // implicit any
  if (condition) return value           // not all paths return
  const unused = "never used"           // unused variable
}

// βœ… These pass strict checking
function goodFunction(input: string): string {
  if (condition) {
    return value
  }
  return defaultValue
}

πŸ§ͺ Testing (Required)

Test Structure

// tests/example.test.ts
import { exampleFunction, ExampleClass } from '@/index'

describe('exampleFunction', () => {
  it('should convert string to uppercase', () => {
    const result = exampleFunction('test')
    expect(result).toBe('TEST')
  })
})

describe('ExampleClass', () => {
  let instance: ExampleClass

  beforeEach(() => {
    instance = new ExampleClass('initial')
  })

  it('should set and get values correctly', () => {
    instance.setValue('new value')
    expect(instance.getValue()).toBe('NEW VALUE')
  })
})

Coverage Requirements

  • Lines: 80% minimum
  • Functions: 100% for public APIs
  • Branches: 80% minimum
  • Statements: 80% minimum

Running Tests

# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

πŸ“š Documentation (Enforced)

JSDoc Required for Public APIs

/**
 * Example function demonstrating strict rules
 * @param input - Input string to process
 * @returns Processed string in uppercase
 */
export const exampleFunction: (input: string) => string = (input: string): string => {
  return input.toUpperCase()
}

/**
 * Example class with strict typing
 */
export class ExampleClass {
  private value: string

  constructor(initialValue: string) {
    this.value = initialValue.toUpperCase()
  }

  /**
   * Get the current value
   * @returns The current value in uppercase
   */
  public getValue(): string {
    return this.value
  }

  /**
   * Set a new value
   * @param newValue - The new value to set
   */
  public setValue(newValue: string): void {
    this.value = newValue.toUpperCase()
  }
}

πŸ” Path Aliases (Clean Imports)

// ❌ Relative imports (messy)
import { utils } from '../../../utils/helper'

// βœ… Path aliases (clean)
import { utils } from '@/utils/helper'
import { types } from '@types/common'
import { helpers } from '@utils/helpers'

Available Path Aliases

  • @/* β†’ src/* (main source directory)
  • @types/* β†’ src/types/* (type definitions)
  • @utils/* β†’ src/utils/* (utility functions)

πŸ› οΈ Development Workflow

1. Start Coding

npm run dev         # Rules are checked

2. Write Tests

npm run test:watch  # TDD approach

3. Quality Check

npm run check-all  # All rules checked

4. Build & Deploy

npm run build      # Production build with minification
npm run docs       # Generate TypeDoc documentation
npm run clean      # Clean build directory

πŸ“„ License

MIT License - see LICENSE file for details.

About

An uncompromisingly strict TypeScript starter template enforcing maximum code quality, type safety, and development best practices.

Topics

Resources

License

Stars

Watchers

Forks

Contributors