Skip to main content

TypeScript: Functions

Typing Functions

When defining a function in TypeScript, you can explicitly specify the types of its parameters and its return type.

function add(a: number, b: number): number {
return a + b;
}

let sum = add(5, 10); // Correct usage
// let result = add(5, "10"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

you can also use function expression syntax

const add = function (a: number, b: number): number {
return a + b;
};

Optional parameters

TypeScript allows you to define optional parameters using the ? syntax. This is useful for functions where some parameters are not always required.

function buildName(firstName: string, lastName?: string): string {
if (lastName) {
return `${firstName} ${lastName}`;
} else {
return firstName;
}
}

Default Parameters

You can also provide default values for parameters, which will be used if no argument is supplied for that parameter.

function greet(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}!`;
}

console.log(greet("Alice")); // Outputs: Hello, Alice!
console.log(greet("Bob", "Good morning")); // Outputs: Good morning, Bob!

Function Overloading

Function overloading allows you to define multiple function signatures for a single function. This is useful when a function can handle different types or numbers of parameters. The actual implementation of the function will handle all the cases defined by the overloads.

// Function overload signatures
function combine(input1: string, input2: string): string;
function combine(input: string): string;

// Function implementation
function combine(input1: string, input2?: string): string {
if (input2 === undefined) {
return input1;
} else {
return input1 + input2;
}
}

// Using the overloaded function
let result1 = combine("Hello", "World"); // "HelloWorld"
let result2 = combine("Hello"); // "Hello"

console.log(result1); // Outputs: HelloWorld
console.log(result2); // Outputs: Hello

here is another example of function overloading combined with union types

// in this instance if we get an object we return a number
function pickCard(x: { suit: string; card: number }[]): number;
// if we get a number we return an object
function pickCard(x: number): { suit: string; card: number };

function pickCard(x: any): any {
if (typeof x === "object") {
let pickedCard = Math.floor(Math.random() * x.length);
return pickedCard;
} else if (typeof x === "number") {
let suits = ["hearts", "spades", "clubs", "diamonds"];
let pickedSuit = suits[Math.floor(x / 13)];
return { suit: pickedSuit, card: x % 13 };
}
}

let myDeck = [
{ suit: "diamonds", card: 2 },
{ suit: "spades", card: 10 },
{ suit: "hearts", card: 4 },
];

let pickedCard1 = myDeck[pickCard(myDeck)];
console.log(`Card: ${pickedCard1.card} of ${pickedCard1.suit}`);

let pickedCard2 = pickCard(15);
console.log(`Card: ${pickedCard2.card} of ${pickedCard2.suit}`);

Automated Amazon Reports

Automatically download Amazon Seller and Advertising reports to a private database. View beautiful, on demand, exportable performance reports.

bidbear.io