This article will show you an example to create a generic function in TypeScript. A generic function is a function that contains a generic syntax to substitute a normal type name of a parameter which allows that parameter to have various types instead of only a single type.
function printout<T, V>(A : T, B : V) { console.log(`${A} ${B}`) }
As you can see there are two parameters that can consist of various types of values on the header of the above function.
Now let’s try to enter a string and a number into the function:-
printout<string, number>("I am number", 1)
Which will show the following outcome:-
I am number 1
Now let’s entered two numbers instead:-
printout<number, number>(2, 1)
Which will show the following outcome:-
2 1
Take notice that you have entered two normal types into the two <> brackets of the above function which means the first parameter has to follow the first type in the bracket and the second parameter has to follow the second type in the bracket! If you don’t want to follow the order of the assignments that appear in the bracket then you can totally ignore the bracket’s types by just entering the below parameters into the function’s header.
printout("Hello", "World!")
Which will show the following outcome:-
Hello World!