Ilg‘or TypeScript


ULASHISH

Node.js uchun kengaytirilgan TypeScript

Ushbu qo‘llanma Node.js ilovalari uchun foydali bo‘lgan ilg‘or TypeScript funksiyalari va naqshlari bilan tanishadi.

To‘liq TypeScript hujjatlari uchun TypeScript qo‘llanmasiga tashrif buyuring.

Kengaytirilgan turdagi tizim xususiyatlari

TypeScript-ning turdagi tizimi mustahkam va xizmat ko‘rsatish mumkin bo‘lgan Node.js ilovalarini yaratish uchun kuchli vositalarni taqdim etadi.

Bu yerda asosiy xususiyatlar:

1. Birlashma va kesishish turlari

// Union type
function formatId(id: string | number) {
  return `ID: ${id}`;
}

// Intersection type
type User = { name: string } & { id: number };

2. Soqchilar turi

type Fish = { swim: () => void };
type Bird = { fly: () => void };

function isFish(pet: Fish | Bird): pet is Fish {
  return 'swim' in pet;
}

3. Ilg‘or generic’lar

// Generic function with constraints
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Generic interface with default type
interface PaginatedResponse<T = any> {
  data: T[];
  total: number;
  page: number;
  limit: number;
}

// Using generic types with async/await in Node.js
async function fetchData<T>(url: string): Promise<T> {
  const response = await fetch(url);
  return response.json();
}

4. Xaritalashtirilgan va shartli turlar

// Mapped types
type ReadonlyUser = {
  readonly [K in keyof User]: User[K];
};

// Conditional types
type NonNullableUser = NonNullable<User | null | undefined>; // User

// Type inference with conditional types
type GetReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
function getUser() {
  return { id: 1, name: 'Alice' } as const;
}
type UserReturnType = GetReturnType<typeof getUser>; // { readonly id: 1; readonly name: "Alice"; }

5. Tip Inference va Type Guards

TypeScript-ning turdagi xulosasi va turi himoyachilari minimal izohlar bilan xavfsiz kodni yaratishga yordam beradi:

// 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 uchun kengaytirilgan TypeScript naqshlari

Ushbu naqshlar ko‘proq xizmat ko‘rsatish va turdagi xavfsiz Node.js ilovalarini yaratishga yordam beradi:

1. Murakkab dekorativlar

// 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. Kengaytirilgan yordamchi dasturlar turlari

// 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<T, K extends keyof T> = Partial<T> & Pick<T, K>;
type UserCreateInput = AtLeast<User, 'name' | 'email'>; // Only name is required

// Create a type that makes specific properties required
WithRequired<T, K extends keyof T> = T & { [P in K]-?: T[P] };
type UserWithEmail = WithRequired<User, 'email'>;

// Extract function return type as a type
type UserFromAPI = Awaited<ReturnType<typeof fetchUser>>;

3. Turi-Xavfsiz hodisa emitentlari

import { EventEmitter } from 'events';

type EventMap = {
  login: (userId: string) => void;
  logout: (userId: string, reason: string) => void;
  error: (error: Error) => void;
};

class TypedEventEmitter<T extends Record<string, (...args: any[]) => void>> {
  private emitter = new EventEmitter();

  on<K extends keyof T>(event: K, listener: T[K]): void {
    this.emitter.on(event as string, listener as any);
  }

  emit<K extends keyof T>(
    event: K,
    ...args: Parameters<T[K]>
  ): boolean {
    return this.emitter.emit(event as string, ...args);
  }
}

// Usage
const userEvents = new TypedEventEmitter<EventMap>();
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 uchun TypeScript eng yaxshi amaliyotlari

Asosiy takliflar:

  • Kod xavfsizligi va ishlab chiquvchilar tajribasini yaxshilash uchun TypeScript-ning ilg‘or turdagi tizimidan foydalaning
  • Turi xavfsizligini yo‘qotmasdan moslashuvchan va qayta foydalanish mumkin bo‘lgan komponentlarni yaratish uchun generiklardan foydalaning
  • Ro‘yxatga olish, tekshirish va ishlash monitoringi kabi o‘zaro bog‘liq masalalar uchun dekorativlarni qo‘llang
  • Kodni takrorlamasdan turlarni o‘zgartirish va boshqarish uchun yordamchi dastur turlaridan foydalaning
  • Hodisa emitentlari va oqimlari kabi Node.js-ga xos naqshlar uchun turdagi xavfsiz abstraktsiyalarni yarating

Umumiylikni hisobga olish:

  • Kompilyatsiya vaqtiga ta’sir qilishi mumkin bo‘lgan murakkab turlarga e’tibor bering
  • Murakkab turdagi operatsiyalar uchun type dan interface dan foydalaning
  • Agar kerak bo‘lsa, so‘zma-so‘z turlari uchun as const dan foydalanishni o‘ylab ko‘ring
  • Turi xavfsiz dinamik yozish uchun any o‘rniga unknown dan foydalaning

To‘liq TypeScript hujjatlari va misollar uchun TypeScript qo‘llanmasiga tashrif buyuring.



W3Schools Pathfinder

Yutuqlaringizni kuzating – bu bepul!