@@ -118,10 +118,10 @@ const square = (x: number): number => x * x;
118118```
119119
120120- ** Default arguments** <br >
121- _ When default parameters are specified, their types are automatically determined by the set values_
121+ _ When default parameters are specified, their types are automatically determined by the passed values_
122122
123123``` ts
124- function getNumbers(max = 99 , min = 0 ): void {}
124+ function getNumbers(max : number = 99 , min = 1 ): void {}
125125```
126126
127127- ** Optional arguments** <br >
@@ -274,3 +274,64 @@ enum Server {
274274 port = 5432
275275}
276276```
277+
278+ ---
279+
280+ ## Generics
281+
282+ - ** Basic usage** <br >
283+ _ Generics allows to create a component that can work over a variety of types rather than a single one_
284+
285+ ``` ts
286+ function test<T >(value : T ): T {
287+ return value ;
288+ }
289+ // "T" will be replaced by the type we specified
290+
291+ test <string >(" Hello World" );
292+ test <number >(2022 );
293+ test <boolean >(true );
294+ ```
295+
296+ - ** Type checking** <br >
297+ _ You can safely use type checking with the ` typeof ` operator to execute the appropriate logic_
298+
299+ ``` ts
300+ function logger<T >(value : T ): void {
301+ if (typeof value == " string" ) {
302+ // we are pretty sure that only strings will get here
303+ console .log (value .toLocaleUpperCase ());
304+ // therefore, we can use string methods
305+ } else if (typeof value == " number" ) {
306+ console .log (value .toFixed (2 ));
307+ } else {
308+ console .log (` ${value } has the ${typeof value } type ` );
309+ }
310+ }
311+
312+ logger <string >(" Hello World" ); // "HELLO WORLD"
313+ logger <number >(2022 ); // 2022.00
314+ logger <boolean >(true ); // "true has the boolean type"
315+ ```
316+
317+ - ** Multiple generics** <br >
318+ _ You can pass multiple generics, for example, to describe different input and output types in functions_
319+
320+ ``` ts
321+ interface IService {
322+ process: <T , S >(data : T ) => S ;
323+ }
324+ ```
325+
326+ - ** Extending generic type** <br >
327+
328+ ``` ts
329+ interface IValue {
330+ info: string ;
331+ }
332+
333+ function test<T extends IValue >(value : T ): T {
334+ console .log (value .info );
335+ return value ;
336+ }
337+ ```
0 commit comments