Generics a cikin TypeScript: Sake amfani da lambar da Ƙara sassaucin lambar

Ma'anar a generics cikin TypeScript siffa ce mai ƙarfi wacce ke haɓaka sassauƙar lamba da haɓaka sake amfani da lambar. Generics ba mu damar ayyana sassauƙa, type-agnostic nau'ikan bayanai a cikin hanyoyin, azuzuwan, da musaya. Wannan yana ba mu damar rubuta hanyoyin da azuzuwan waɗanda za su iya aiki tare da nau'ikan bayanai da yawa.

Amfanin cikin generics sun TypeScript haɗa da:

 

Maimaita Code

Generics ba mu damar rubuta lamba sau ɗaya kuma mu sake amfani da shi don nau'ikan bayanai daban-daban. Maimakon rubuta hanyoyi masu kama da juna ko azuzuwan ga kowane takamaiman nau'in bayanai, za mu iya amfani da shi generics don ƙirƙirar lambar ƙira wacce za a iya sake amfani da ita don nau'ikan bayanai da yawa.

 

Duban Nau'in A tsaye

Generics ba TypeScript da damar yin duban nau'in tsaye, tabbatar da daidaito da hana kurakurai lokacin amfani da nau'ikan bayanai marasa kuskure. Wannan yana taimaka mana ganowa da gyara kurakurai cikin sauri cikin aminci.

 

Ƙarar Ƙaƙwalwar Ƙaddamarwa

Generics fadada iyawar hanyoyin, azuzuwan, da mu'amala don aiki tare da nau'ikan bayanai daban-daban. Za mu iya ƙirƙira mafi sassauƙa da tsarin bayanai daban-daban, marasa ƙuntatawa ta takamaiman nau'in bayanai.

Misali:

function reverse<T>(array: T[]): T[] {  
  return array.reverse();  
}  
  
const numbers = [1, 2, 3, 4, 5];  
const reversedNumbers = reverse(numbers);  
console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]  
  
const strings = ["apple", "banana", "orange"];  
const reversedStrings = reverse(strings);  
console.log(reversedStrings); // Output: ["orange", "banana", "apple"]  

A cikin misalin da ke sama, muna amfani generics da rubuta reverse aikin da zai iya aiki tare da tsararru na kowane nau'in bayanai. Za mu iya sake amfani da wannan aikin don duka jeri-jerun lambobi da tsararrun kirtani, yayin da muke ci gaba da kiyaye nau'in dubawa.

 

A taƙaice, manufar generics in TypeScript tana haɓaka sassaucin lamba kuma yana ba da damar sake amfani da lambar. Yana ba mu damar rubuta lambar ƙira wacce za ta iya aiki tare da nau'ikan bayanai da yawa, haɓaka sassauci, nau'in aminci, da ingancin lambar.