@@ -13,63 +13,63 @@ We do not need comments most of the time.
1313### ❌ AVOID These Comment Types
1414
1515** Obvious Comments**
16- ``` javascript
16+ ``` typescript
1717// Bad: States the obvious
18- let counter = 0 ; // Initialize counter to zero
18+ let counter: number = 0 ; // Initialize counter to zero
1919counter ++ ; // Increment counter by one
2020```
2121
2222** Redundant Comments**
23- ``` javascript
23+ ``` typescript
2424// Bad: Comment repeats the code
25- function getUserName () {
25+ function getUserName(user : User ) : string {
2626 return user .name ; // Return the user's name
2727}
2828```
2929
3030** Outdated Comments**
31- ``` javascript
31+ ``` typescript
3232// Bad: Comment doesn't match the code
3333// Calculate tax at 5% rate
34- const tax = price * 0.08 ; // Actually 8%
34+ const tax: number = price * 0.08 ; // Actually 8%
3535```
3636
3737### ✅ WRITE These Comment Types
3838
3939** Complex Business Logic**
40- ``` javascript
40+ ``` typescript
4141// Good: Explains WHY this specific calculation
4242// Apply progressive tax brackets: 10% up to 10k, 20% above
43- const tax = calculateProgressiveTax (income, [0.10 , 0.20 ], [10000 ]);
43+ const tax: number = calculateProgressiveTax (income , [0.10 , 0.20 ], [10000 ]);
4444```
4545
4646** Non-obvious Algorithms**
47- ``` javascript
47+ ``` typescript
4848// Good: Explains the algorithm choice
4949// Using Floyd-Warshall for all-pairs shortest paths
5050// because we need distances between all nodes
51- for (let k = 0 ; k < vertices; k++ ) {
52- for (let i = 0 ; i < vertices; i++ ) {
53- for (let j = 0 ; j < vertices; j++ ) {
51+ for (let k: number = 0 ; k < vertices ; k ++ ) {
52+ for (let i: number = 0 ; i < vertices ; i ++ ) {
53+ for (let j: number = 0 ; j < vertices ; j ++ ) {
5454 // ... implementation
5555 }
5656 }
5757}
5858```
5959
6060** Regex Patterns**
61- ``` javascript
61+ ``` typescript
6262// Good: Explains what the regex matches
6363// Match email format: username@domain.extension
64- const emailPattern = / ^ [a-zA-Z0-9 . _%+-] + @[a-zA-Z0-9 . -] + \. [a-zA-Z ] {2,} $ / ;
64+ const emailPattern: RegExp = / ^ [a-zA-Z0-9 . _%+-] + @[a-zA-Z0-9 . -] + \. [a-zA-Z ] {2,} $ / ;
6565```
6666
6767** API Constraints or Gotchas**
68- ``` javascript
68+ ``` typescript
6969// Good: Explains external constraint
7070// GitHub API rate limit: 5000 requests/hour for authenticated users
7171await rateLimiter .wait ();
72- const response = await fetch (githubApiUrl);
72+ const response: Response = await fetch (githubApiUrl );
7373```
7474
7575## Decision Framework
@@ -83,26 +83,36 @@ Before writing a comment, ask:
8383## Special Cases for Comments
8484
8585### Public APIs
86- ``` javascript
86+ ``` typescript
8787/**
8888 * Calculate compound interest using the standard formula.
89- *
90- * @param {number} principal - Initial amount invested
91- * @param {number} rate - Annual interest rate (as decimal, e.g., 0.05 for 5%)
92- * @param {number} time - Time period in years
93- * @param {number} compoundFrequency - How many times per year interest compounds (default: 1)
94- * @returns {number} Final amount after compound interest
89+ * @param principal - Initial amount invested
90+ * @param rate - Annual interest rate (as decimal, e.g., 0.05 for 5%)
91+ * @param time - Time period in years
92+ * @param compoundFrequency - How many times per year interest compounds (default: 1)
93+ * @returns Final amount after compound interest
94+ * @example
95+ * ```typescript
96+ * const result = calculateCompoundInterest(1000, 0.05, 2, 12);
97+ * console.log(result); // 1104.54
98+ * ```
99+ * @throws {Error} When principal is negative or rate/time are invalid
95100 */
96- function calculateCompoundInterest (principal , rate , time , compoundFrequency = 1 ) {
97- // ... implementation
101+ function calculateCompoundInterest(
102+ principal : number ,
103+ rate : number ,
104+ time : number ,
105+ compoundFrequency : number = 1
106+ ): number {
107+ // ... implementation
98108}
99109```
100110
101111### Configuration and Constants
102- ``` javascript
112+ ``` typescript
103113// Good: Explains the source or reasoning
104- const MAX_RETRIES = 3 ; // Based on network reliability studies
105- const API_TIMEOUT = 5000 ; // AWS Lambda timeout is 15s, leaving buffer
114+ const MAX_RETRIES: number = 3 ; // Based on network reliability studies
115+ const API_TIMEOUT: number = 5000 ; // AWS Lambda timeout is 15s, leaving buffer
106116```
107117
108118### Annotations
@@ -119,27 +129,159 @@ const API_TIMEOUT = 5000; // AWS Lambda timeout is 15s, leaving buffer
119129// DEPRECATED: Use newApiFunction() instead - this will be removed in v3.0
120130```
121131
132+ ## TSDoc Standards and File Headers
133+
134+ ### File Headers
135+ ``` typescript
136+ /**
137+ * @fileoverview User authentication utilities for the application.
138+ * Provides secure login, logout, and session management functions.
139+ *
140+ * @author Development Team
141+ * @copyright 2025 Company Name. All rights reserved.
142+ * @license MIT
143+ */
144+
145+ import { User } from ' ./types' ;
146+
147+ /**
148+ * Authenticates a user with email and password.
149+ * @param email - User's email address
150+ * @param password - User's password
151+ * @returns Promise resolving to authenticated user or null
152+ * @throws {AuthenticationError} When credentials are invalid
153+ */
154+ export async function authenticateUser(email : string , password : string ): Promise <User | null > {
155+ // implementation
156+ }
157+ ```
158+
159+ ### Common TSDoc Tags
160+ ``` typescript
161+ /**
162+ * Processes user data with validation and transformation.
163+ *
164+ * @param user - The user object to process, must have valid id and name
165+ * @param options - Processing options including validation flags
166+ * @returns Promise<UserProfile> - The processed user profile with additional data
167+ * @throws {ValidationError} When user data fails validation
168+ * @throws {NetworkError} When API calls fail
169+ * @see {@link validateUser } for validation logic
170+ * @see {@link transformUserData } for transformation details
171+ * @example
172+ * ```typescript
173+ * const user = { id: 1, name: 'John' };
174+ * const profile = await processUser(user, { validate: true });
175+ * ```
176+ * @beta This API is in beta and may change
177+ * @internal For internal use only
178+ */
179+ async function processUser(user : User , options : ProcessingOptions ): Promise <UserProfile > {
180+ // implementation
181+ }
182+ ```
183+
184+ ### Type Documentation
185+ ``` typescript
186+ /**
187+ * Represents a user in the system.
188+ * @public
189+ */
190+ export interface User {
191+ /** Unique identifier for the user */
192+ readonly id: number ;
193+ /** User's full name */
194+ name: string ;
195+ /** User's email address */
196+ email: string ;
197+ /** Optional profile picture URL */
198+ avatarUrl? : string ;
199+ }
200+
201+ /**
202+ * Generic result type for API operations.
203+ * @template T - The type of the successful result
204+ * @template E - The type of the error
205+ */
206+ export type Result <T , E = Error > = { success: true ; data: T } | { success: false ; error: E };
207+ ```
208+
209+ ### Interface and Type Definitions
210+ ``` typescript
211+ /**
212+ * User profile extending base user with optional personalization data.
213+ * Used for user dashboard and profile management features.
214+ * @public
215+ */
216+ interface UserProfile extends User {
217+ /** Optional biography text */
218+ bio? : string ;
219+ /** Profile picture URL */
220+ avatarUrl? : string ;
221+ }
222+ ```
223+
224+ ### Generics
225+ ``` typescript
226+ /**
227+ * Serializes data to JSON string with type safety.
228+ * @template T - Data type that must be serializable
229+ * @param data - The data to serialize
230+ * @returns JSON string representation
231+ * @throws {TypeError} When data cannot be serialized
232+ */
233+ function serializeResponse<T extends Serializable >(data : T ): string {
234+ return JSON .stringify (data );
235+ }
236+ ```
237+
238+ ### Type Guards
239+ ``` typescript
240+ /**
241+ * Type guard to check if value is a valid User object.
242+ * Performs runtime validation of required User fields.
243+ * @param value - Unknown value to test
244+ * @returns True if value is a User with required fields
245+ */
246+ function isUser(value : unknown ): value is User {
247+ return typeof value === ' object' && value !== null && ' name' in value && ' id' in value ;
248+ }
249+ ```
250+
251+ ### Advanced Types
252+ ``` typescript
253+ /**
254+ * Creates a deep readonly version of any type T.
255+ * Recursively applies readonly modifier to all nested objects and arrays.
256+ * Useful for immutable data structures and preventing accidental mutations.
257+ * @template T - The type to make readonly
258+ */
259+ type ReadonlyDeep <T > = {
260+ readonly [P in keyof T ]: T [P ] extends object ? ReadonlyDeep <T [P ]> : T [P ];
261+ };
262+ ```
263+
122264## Anti-Patterns to Avoid
123265
124266### Dead Code Comments
125- ``` javascript
267+ ``` typescript
126268// Bad: Don't comment out code
127269// const oldFunction = () => { ... };
128- const newFunction = () => { ... };
270+ const newFunction = (): void => { ... };
129271```
130272
131273### Changelog Comments
132- ``` javascript
274+ ``` typescript
133275// Bad: Don't maintain history in comments
134276// Modified by John on 2023-01-15
135277// Fixed bug reported by Sarah on 2023-02-03
136- function processData () {
278+ function processData(): void {
137279 // ... implementation
138280}
139281```
140282
141283### Divider Comments
142- ``` javascript
284+ ``` typescript
143285// Bad: Don't use decorative comments
144286// =====================================
145287// UTILITY FUNCTIONS
@@ -148,13 +290,21 @@ function processData() {
148290
149291## Quality Checklist
150292
151- Before committing, ensure your comments:
152- - [ ] Explain WHY, not WHAT
153- - [ ] Are grammatically correct and clear
154- - [ ] Will remain accurate as code evolves
155- - [ ] Add genuine value to code understanding
156- - [ ] Are placed appropriately (above the code they describe)
157- - [ ] Use proper spelling and professional language
293+ Before committing, ensure:
294+ - [ ] Comments explain WHY, not WHAT
295+ - [ ] Comments are grammatically correct and clear
296+ - [ ] Comments will remain accurate as code evolves
297+ - [ ] Comments add genuine value to code understanding
298+ - [ ] Comments are placed appropriately (above the code they describe)
299+ - [ ] Comments use proper spelling and professional language
300+ - [ ] Code includes error handling and edge cases
301+ - [ ] Code has testable structure with clear inputs/outputs
302+ - [ ] Code follows extensible design for future modifications
303+ - [ ] Code considers performance where relevant
304+ - [ ] Code has clear documentation that explains business logic
305+ - [ ] Code follows established best practices and standards
306+ - [ ] Code is readable for maintenance and collaboration
307+ - [ ] Code maintains proper abstraction and separation of concerns
158308
159309## Summary
160310
0 commit comments