1interface Lengthwise {
2 length: number;
3}
4
5function loggingIdentity<T extends Lengthwise>(arg: T): T {
6 console.log(arg.length); // Now we know it has a .length property, so no more error
7 return arg;
8}
9
1class Person<T, U, C> {
2 name: T
3 age: U
4 hobby: C[]
5
6 constructor(name: T, age: U, hobby: C[]) {
7 this.name = name
8 this.age = age
9 this.hobby = hobby
10 }
11}
12
13const output = new Person<string, number, string>('john doe', 23, ['swimming', 'traveling', 'badminton'])
14console.log(output)
1function firstElement<Type>(arr: Type[]): Type {
2 return arr[0];
3}
4// s is of type 'string'
5const s = firstElement(["a", "b", "c"]);
6// n is of type 'number'
7const n = firstElement([1, 2, 3]);
1class GenericNumber<T> {
2 zeroValue: T;
3 add: (x: T, y: T) => T;
4}
5
6let myGenericNumber = new GenericNumber<number>();
7myGenericNumber.zeroValue = 0;
8myGenericNumber.add = function(x, y) { return x + y; };
9