# More on Functions
- My question on Stackoverflow (opens new window)
# Function type expression
// def - (param:type) => returnType;
type callback = (x: string) => string;
// as arg
function foo(func: callback) {
func('hello');
}
// as arrow function
const bar: callback = (str) => {
return str;
};
# Signature
- Use this if callback has some extra properties in addition to function defination
|
|
# Generic Functions
- Use Generics when we have 2+ related variables ie used atleast 2 times.
- If no relation then don't use it.
|
|
# Generic + constraint
Note : if
extends
is used then it can have more properties than what it extends.
|
|
# Overload
- Avoid Overload if Union can be used.
// overload signatures (atleast 2+)
function foo(num: number): number;
function foo(x: number, y: number): number;
// function implementation
function foo(xOrNum: number, y?: number): number {
if (y) return xOrNum + y;
return xOrNum * 2;
}
console.log(foo(3)); // 6
console.log(foo(3, 5)); // 8