typescript generic function code example
Example 1: extend generics in functions typescript
interface Lengthwise {
length: number;
}
function loggingIdentity(arg: T): T {
console.log(arg.length); // Now we know it has a .length property, so no more error
return arg;
}
Example 2: typescript generic class
class Person {
name: T
age: U
hobby: C[]
constructor(name: T, age: U, hobby: C[]) {
this.name = name
this.age = age
this.hobby = hobby
}
}
const output = new Person('john doe', 23, ['swimming', 'traveling', 'badminton'])
console.log(output)
Example 3: typescript generic function
function firstElement(arr: Type[]): Type {
return arr[0];
}
// s is of type 'string'
const s = firstElement(["a", "b", "c"]);
// n is of type 'number'
const n = firstElement([1, 2, 3]);
Example 4: typescript class type t
class GenericNumber {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x + y; };
Example 5: typescript generic type
function identity(arg: T): T {
return arg;
}Try
Example 6: how to make a generic variable in javascript
var x = 1;
var y = 1;
if (x == y) {
x = x + 1
}