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}`);

Recent Work

Free desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.

Learn More
slide-6
slide-5
slide-2
slide-1
slide-3
slide-4
Technologies Used
TypeScript
Electron
React

BidBear

bidbear.io

Bidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.

Learn More
slide-1
slide-2
slide-5
slide-3
slide-4

Technologies Used

Front End
JavaScript
Docker
React
Redux
Vite
Next
Docusaurus
Stripe
Sentry
D3
React-Flow
TipTap
Back End
JavaScript
Python
AWS CognitoCognito
AWS API GatewayAPI Gateway
AWS LambdaLambda
AWS AthenaAthena
AWS GlueGlue
AWS Step FunctionsStep Functions
AWS SQSSQS
AWS DynamoDBDynamo DB
AWS S3S3
AWS CloudwatchCloudWatch
AWS CloudFrontCloudFront
AWS Route 53Route 53
AWS EventBridgeEventBridge