Kishore Prabhu’s Post

In TypeScript, generics play a crucial role when you want to write reusable and type-safe code. They help ensure that your functions, classes, and components work with any data type without losing type safety at compile time. Let's look at some examples. 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗚𝗲𝗻𝗲𝗿𝗶𝗰𝘀: If you define an array without specifying a strict type, TypeScript tries to infer it based on the values you insert. 𝗹𝗲𝘁 𝗮𝗿𝗿𝗮𝘆𝗡𝗼𝗿𝗺𝗮𝗹 = ["𝗮", "𝗯", "𝗰", 𝟭]; TypeScript infers the type as "(string | number)[]". This could lead to unexpected behaviour. 𝗪𝗶𝘁𝗵 𝗚𝗲𝗻𝗲𝗿𝗶𝗰𝘀: Let’s define a generic function: 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗴𝗲𝘁𝗔𝗿𝗿𝗮𝘆<𝗧>(𝗮𝗿𝗴𝘀: 𝗔𝗿𝗿𝗮𝘆<𝗧>): 𝗔𝗿𝗿𝗮𝘆<𝗧> { 𝗿𝗲𝘁𝘂𝗿𝗻 𝗮𝗿𝗴𝘀; } In the above function, "T" refers to the data type; it can be a number, string, or any user-defined type. Now let’s invoke the above generic function with the same array "(["a", "b", "c", 1])": 𝗹𝗲𝘁 𝗮𝗿𝗿𝗮𝘆𝗚𝗲𝗻𝗲𝗿𝗶𝗰 = 𝗴𝗲𝘁𝗔𝗿𝗿𝗮𝘆<𝘀𝘁𝗿𝗶𝗻𝗴>(["𝗮", "𝗯", "𝗰", 𝟭]); 𝗧𝘆𝗽𝗲𝗦𝗰𝗿𝗶𝗽𝘁 𝗶𝗺𝗺𝗲𝗱𝗶𝗮𝘁𝗲𝗹𝘆 𝘁𝗵𝗿𝗼𝘄𝘀 𝗮𝗻 𝗲𝗿𝗿𝗼𝗿: Type "number" is not assignable to type 'string'. This helps catch the error before your code runs. The proper way to define a type string array using generics: 𝗹𝗲𝘁 𝗮𝗿𝗿𝗮𝘆𝗚𝗲𝗻𝗲𝗿𝗶𝗰 = 𝗴𝗲𝘁𝗔𝗿𝗿𝗮𝘆<𝘀𝘁𝗿𝗶𝗻𝗴>(["𝗮", "𝗯", "𝗰"]); 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 1. Prevent runtime bugs by catching type errors early. 2. Improve code reusability and maintainability. 3. Write flexible, type-safe code. Let’s continue learning about generics in the next post. #typescript #web #javascript #tech #learning

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories