YouTip LogoYouTip

Ts Generics

Generics is a programming language feature that allows using placeholders to represent types when defining functions, classes, interfaces, etc., rather than specific types. Generics is a very useful feature when writing reusable, flexible, and type-safe code. The main purpose of using generics is to handle data that is not of a specific type, so that the code can be applied to multiple data types without losing type checking. **The advantages of generics include:** * **Code Reusability:** You can write general code that is independent of specific types, improving code reusability. * **Type Safety:** Type checking is performed at compile time to avoid type errors at runtime. * **Abstraction:** Allows writing more abstract and general code that adapts to different data types and data structures. ### Generic Identifiers In generics, some conventional identifiers are usually used, such as common `T` (representing Type), `U`, `V`, etc., but you can actually use any identifier. T: Stands for "Type", and is the most common generic type parameter name. function identity(arg: T): T { return arg;} K, V: Used to represent generic type parameters for keys (Key) and values (Value). interface KeyValuePair { key: K; value: V;} E: Used to represent generic type parameters for array elements. function printArray(arr: E[]): void { arr.forEach(item => console.log(item));} R: Used to represent generic type parameters for function return values. function getResult(value: R): R { return value;} U, V: Usually used to represent the second and third generic type parameters. function combine(first: U, second: V): string { return `${first} ${second}`;} These identifiers are conventional; in fact, you can choose any name that conforms to identifier specifications. The key is to make the code readable and easy to understand, so it is recommended to use descriptive names on generic type parameters to make their purpose easy to understand. ### Generic Functions (Generic Functions) Use generics to create a function that can handle different types: ## Example function identity(arg: T): T { return arg; } // Using generic functions let result = identity("Hello"); console.log(result);// Output: Hello let numberResult = identity(42); console.log(numberResult);// Output: 42 **Explanation:** In the above example, `identity` is a generic function, using `` to represent the generic type. It accepts a parameter `arg` and the return value are both of the generic type `T`. When using it, you can explicitly specify the generic type through angle brackets ``. The first call specifies the `string` type, and the second call specifies the `number` type. ### 2. Generic Interfaces (Generic Interfaces) You can use generics to define interfaces so that interface members can use any type: ## Example // Basic syntax interface Pair{ first: T; second: U; } // Using generic interfaces let pair: Pair={ first:"hello", second:42}; console.log(pair);// Output: { first: 'hello', second: 42 } **Explanation:** Here, a generic interface `Pair` is defined with two type parameters `T` and `U`. Then, using this generic interface, an object `pair` is created, where `first` is of string type and `second` is of number type. ### 3. Generic Classes (Generic Classes) Generics can also be applied to instance variables and methods of classes: ## Example // Basic syntax class Box{ private value: T; constructor(value: T){ this.value= value; } getValue(): T { return this.value; } } // Using generic classes let stringBox =new Box("TypeScript"); console.log(stringBox.getValue());// Output: TypeScript **Explanation:** In this example, `Box` is a generic class, using `` to represent the generic type. Both the constructor and methods can use the generic type `T`. By instantiating `Box`, we create a `Box` instance that stores strings, and retrieve the stored value through the `getValue` method. ### 4. Generic Constraints (Generic Constraints) Sometimes you want to limit the type range of generics, you can use generic constraints: ## Example // Basic syntax interface Lengthwise { length: number; } function logLength(arg: T):void{ console.log(arg.length); } // Correct usage logLength("hello");// Output: 5 // Incorrect usage, because numbers do not have length property logLength(42);// Error **Explanation:** In this example, a generic function `logLength` is defined that accepts a parameter of type `T`, but has a constraint that `T` must implement the `Lengthwise` interface, which requires a `length` property. Therefore, `logLength("hello")` can be called correctly, but `logLength(42)` cannot be called because numbers do not have a `length` property. ### 5. Generics with Default Values You can set default values for generics so that default types can be used when type parameters are not specified: ## Example // Basic syntax function defaultValue(arg: T): T { return arg; } // Using generic functions with default values let result1 = defaultValue("hello");// Inferred as string type let result2 = defaultValue(42);// Inferred as number type **Description:** This example demonstrates a generic function with default values. The function `defaultValue` accepts a generic parameter `T` and sets its default type to `string`. When using it, if no type is explicitly specified, the default type is used. In the example, `result1` is inferred as `string` type in the first call, and `result2` is inferred as `number` type in the second call.
← Python Stock Line ChartQt Cumulative β†’