Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 1x 4x 1x 4x 4x 1x 4x 1x 4x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x | // Generic Function
export function identity<T>(value: T): T {
return value;
}
// Generic Interface
export interface Box<T> {
value: T;
}
// Generic Class
export class Container<T> {
private readonly _value: T;
constructor(value: T) {
this._value = value;
}
getValue(): T {
return this._value;
}
}
// Generic Constraints
export function getLength<T extends { length: number }>(value: T): number {
return value.length;
}
// Using Multiple Generics
export function pair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
export function generics(): void {
console.log(`\n### Generics ###`)
const numberIdentity = identity(42); // T is inferred as number
console.log(`Identity of number: ${numberIdentity}`);
const stringIdentity = identity("Hello, TypeScript!"); // T is inferred as string
console.log(`Identity of string: ${stringIdentity}`);
// Using Generic Interface (Box)
const box: Box<string> = {value: "This is a box!"};
console.log(`Box value: ${box.value}`);
// Using Generic Class (Container)
const numberContainer = new Container<number>(100);
console.log(`Container value: ${numberContainer.getValue()}`);
const stringContainer = new Container<string>("Generics in action");
console.log(`Container value: ${stringContainer.getValue()}`);
// Using Generic Constraints (getLength)
const arrayLength = getLength([1, 2, 3, 4, 5]); // T is inferred as array
console.log(`Length of array: ${arrayLength}`);
const stringLength = getLength("Hello, world!"); // T is inferred as string
console.log(`Length of string: ${stringLength}`);
// Using Multiple Generics (pair)
const numberPair = pair(1, "one");
console.log(`Pair: ${numberPair[0]} and ${numberPair[1]}`);
const stringPair = pair("Hello", "World");
console.log(`Pair: ${stringPair[0]} and ${stringPair[1]}`);
}
|