Node.js க்கான மேம்பட்ட TypeScript
இந்த வழிகாட்டி Node.js பயன்பாடுகளுக்கு குறிப்பாக பயனுள்ள மேம்பட்ட TypeScript அம்சங்கள் மற்றும் வடிவங்களை ஆராய்கிறது.
விரிவான TypeScript ஆவணங்களுக்கு:
விரிவான TypeScript ஆவணங்களுக்கு எங்கள் TypeScript டுடோரியலைப் பார்வையிடவும்.
மேம்பட்ட வகை அமைப்பு அம்சங்கள்
TypeScript இன் வகை அமைப்பு வலுவான மற்றும் பராமரிக்கக்கூடிய Node.js பயன்பாடுகளை உருவாக்க சக்திவாய்ந்த கருவிகளை வழங்குகிறது.
இங்கே முக்கிய அம்சங்கள் உள்ளன:
1. யூனியன் மற்றும் இன்டர்செக்ஷன் வகைகள்
// Union type
function formatId(id: string | number) {
return `ID: ${id}`;
}
// Intersection type
type User = { name: string } & { id: number };
2. வகை கார்டுகள்
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function isFish(pet: Fish | Bird): pet is Fish {
return 'swim' in pet;
}
3. மேம்பட்ட ஜெனரிக்ஸ்
// Generic function with constraints
function getProperty(obj: T, key: K): T[K] {
return obj[key];
}
// Generic interface with default type
interface PaginatedResponse {
data: T[];
total: number;
page: number;
limit: number;
}
// Using generic types with async/await in Node.js
async function fetchData(url: string): Promise {
const response = await fetch(url);
return response.json();
}
4. மேப்பட் மற்றும் கண்டிஷனல் வகைகள்
// Mapped types
type ReadonlyUser = {
readonly [K in keyof User]: User[K];
};
// Conditional types
type NonNullableUser = NonNullable; // User
// Type inference with conditional types
type GetReturnType = T extends (...args: any[]) => infer R ? R : never;
function getUser() {
return { id: 1, name: 'Alice' } as const;
}
type UserReturnType = GetReturnType; // { readonly id: 1; readonly name: "Alice"; }
5. வகை உட்கணிப்பு மற்றும் வகை கார்டுகள்
TypeScript இன் வகை உட்கணிப்பு மற்றும் வகை கார்டுகள் குறைந்தமான குறிப்புகளுடன் வகை-பாதுகாப்பான குறியீட்டை உருவாக்க உதவுகின்றன:
// Type inference with variables
const name = 'Alice'; // TypeScript infers type: string
const age = 30; // TypeScript infers type: number
const active = true; // TypeScript infers type: boolean
// Type inference with arrays
const numbers = [1, 2, 3]; // TypeScript infers type: number[]
const mixed = [1, 'two', true]; // TypeScript infers type: (string | number | boolean)[]
// Type inference with functions
function getUser() {
return { id: 1, name: 'Alice' }; // Return type inferred as { id: number; name: string; }
}
const user = getUser(); // user inferred as { id: number; name: string; }
console.log(user.name); // Type checking works on inferred properties
Node.js க்கான மேம்பட்ட TypeScript வடிவங்கள்
இந்த வடிவங்கள் மேலும் பராமரிக்கக்கூடிய மற்றும் வகை-பாதுகாப்பான Node.js பயன்பாடுகளை உருவாக்க உதவுகின்றன:
1. மேம்பட்ட டெகோரேட்டர்கள்
// Parameter decorator with metadata
function validateParam(target: any, key: string, index: number) {
const params = Reflect.getMetadata('design:paramtypes', target, key) || [];
console.log(`Validating parameter ${index} of ${key} with type ${params[index]?.name}`);
}
// Method decorator with factory
function logExecutionTime(msThreshold = 0) {
return function (target: any, key: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = async function (...args: any[]) {
const start = Date.now();
const result = await originalMethod.apply(this, args);
const duration = Date.now() - start;
if (duration > msThreshold) {
console.warn(`[Performance] ${key} took ${duration}ms`);
}
return result;
};
};
}
class ExampleService {
@logExecutionTime(100)
async fetchData(@validateParam url: string) {
// Implementation
}
}
2. மேம்பட்ட பயன்பாட்டு வகைகள்
// Built-in utility types with examples interface User {
id: number;
name: string;
email?: string;
createdAt: Date;
}
// Create a type with specific properties as required
type AtLeast = Partial & Pick;
type UserCreateInput = AtLeast; // Only name is required
// Create a type that makes specific properties required
WithRequired = T & { [P in K]-?: T[P] };
type UserWithEmail = WithRequired;
// Extract function return type as a type
type UserFromAPI = Awaited>;
3. வகை-பாதுகாப்பான நிகழ்வு எமிட்டர்கள்
import { EventEmitter } from 'events';
type EventMap = {
login: (userId: string) => void;
logout: (userId: string, reason: string) => void;
error: (error: Error) => void;
};
class TypedEventEmitter void>> {
private emitter = new EventEmitter();
on(event: K, listener: T[K]): void {
this.emitter.on(event as string, listener as any);
}
emit(
event: K,
...args: Parameters
): boolean {
return this.emitter.emit(event as string, ...args);
}
}
// Usage
const userEvents = new TypedEventEmitter();
userEvents.on('login', (userId) => {
console.log(`User ${userId} logged in`);
});
// TypeScript will show an error for incorrect argument types
// userEvents.emit('login', 123);
// Error: Argument of type 'number' is not assignable to 'string'
Node.js க்கான TypeScript சிறந்த நடைமுறைகள்
முக்கிய கருத்துக்கள்:
மேம்பட்ட வகை அமைப்பைப் பயன்படுத்தவும்
சிறந்த குறியீடு பாதுகாப்பு மற்றும் டெவலப்பர் அனுபவத்திற்காக TypeScript இன் மேம்பட்ட வகை அமைப்பைப் பயன்படுத்தவும்
ஜெனரிக்ஸைப் பயன்படுத்தவும்
வகை பாதுகாப்பை இழக்காமல் நெகிழ்வான மற்றும் மீண்டும் பயன்படுத்தக்கூடிய கூறுகளை உருவாக்க ஜெனரிக்ஸைப் பயன்படுத்தவும்
டெகோரேட்டர்களை செயல்படுத்தவும்
லாக்கிங், சரிபார்ப்பு மற்றும் செயல்திறன் மானிட்டரிங் போன்ற குறுக்கு-வெட்டு கவலைகளுக்கு டெகோரேட்டர்களை செயல்படுத்தவும்
பயன்பாட்டு வகைகளைப் பயன்படுத்தவும்
குறியீடு நகலெடுப்பு இல்லாமல் வகைகளை மாற்ற மற்றும் கையாள பயன்பாட்டு வகைகளைப் பயன்படுத்தவும்
வகை-பாதுகாப்பான அம்சங்களை உருவாக்கவும்
நிகழ்வு எமிட்டர்கள் மற்றும் ஸ்ட்ரீம்கள் போன்ற Node.js-குறிப்பிட்ட வடிவங்களுக்கு வகை-பாதுகாப்பான அம்சங்களை உருவாக்கவும்
செயல்திறன் பரிசீலனைகள்:
விரிவான TypeScript ஆவணங்களுக்கு:
விரிவான TypeScript ஆவணங்கள் மற்றும் எடுத்துக்காட்டுகளுக்கு எங்கள் TypeScript டுடோரியலைப் பார்வையிடவும்.