Generics
-
Rule: Use generics to create reusable and flexible components that work with any data type.
-
Reason: Generics allow you to write functions, classes, and interfaces that can handle multiple data types while maintaining type safety.
Example:
function identity<T>(arg: T): T {
return arg;
}
// Usage
const num = identity<number>(42);
const str = identity<string>('hello');
// Generic interface
interface Repository<T> {
getById(id: number): T;
getAll(): T[];
save(item: T): void;
}
// Generic class
class ArrayWrapper<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
get(index: number): T {
return this.items[index];
}
}
Compilation
-
Rule: Configure the TypeScript compiler (
tsc) using atsconfig.jsonfile to target specific ECMAScript versions and manage other compiler options. -
Reason: Proper configuration of
tsconfig.jsonensures compatibility with different JavaScript environments and fine-tuning of the TypeScript compiler.
Example (tsconfig.json):
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
Summary:
- Generics SHOULD be used for reusable, type-safe components.
- tsconfig.json MUST be used to configure TypeScript compilation.