How functions are defined for modularity in different languages.
Functions
Functions
none
typescript
TypeScript Functions
Function Definition with Arguments and a Return Type
How to pass arguments to a function and express the return type.
Error Loading
Missing
Function Definition with Arguments and Return Type
TypeScript allows specifying argument types and return types explicitly in function definitions.
function add(x: number, y: number): number { return x + y; } const greet = (name: string): string => `Hello, ${name}!`;
x: number, y: number
: Defines parameter types.: number
after()
specifies the return type.
Function Overloading
Provide multiple implementations with different sets of arguments.
Missing
Function overloading processed at runtime
function add(x: number, y: number): number; function add(x: string, y: string): string; function add(x: any, y: any): any { return x + y; } console.log(add(5, 10)); // 15 console.log(add("Hello, ", "World!")); // "Hello, World!"
Default or Optional Arguments
Provide defaults or express optionality in arguments.
Missing
Function Default Arguments
function doIt(b: number, a = 1) { return b / a; } console.log("DoIt " + doIt(10) + " " + doIt(10, 2));
Lambda Functions
Define a lambda function.
Missing
const doIt = (b: number, c: number) => a * b; console.log("DoIt " + doIt(10, 5));
Lambda Function Capture
Use local in-scope variables inside the lambda function.
Missing
function createCounter(): () => number { let count = 0; // This variable is captured by the closure return () => { count += 1; return count; }; } const counterA = createCounter(); console.log(counterA()); // 1 console.log(counterA()); // 2 const counterB = createCounter(); console.log(counterB()); // 1 (separate closure) console.log(counterA()); // 3 (original closure still intact)
function makeMultiplier(factor: number): (input: number) => number { // factor is captured by the inner function return (input: number) => input * factor; } const double = makeMultiplier(2); const triple = makeMultiplier(3); console.log(double(5)); // 10 console.log(triple(5)); // 15
Function Type Parameter (Generics)
Define a function with one or more types as an argument.
Missing
Function Generics
function identity<T>(value: T): T { return value; } console.log(identity<number>(42)); // 42 console.log(identity<string>("Hello")); // "Hello"
Function Type Parameter Constraints
Define constraints on the type parameter.
Missing
Function Generics Constraint
And with a constraint:
function getLength<T extends { length: number }>(arg: T): number { return arg.length; } console.log(getLength("Hello")); // 5 console.log(getLength([1, 2, 3])); // 3