Functions in TypeScript
Write code once and use it again! Learn how TypeScript functions accept information, perform tasks, and return results — with types that help prevent mistakes.
function greet(name: string)
: string {
return `Hello, ${name}!`;
}
console.log(
greet("Alex")
);
Write It Once, Use It Again
Imagine building a website that welcomes every visitor. You could write a separate greeting for each person, but that would quickly become repetitive.
A function lets you group instructions under a name and run those instructions whenever you need them.
function sayHello(): void {
console.log("Hello from mC0de!");
}
sayHello();
sayHello();
The function’s instructions are written once but executed twice. Calling sayHello() tells TypeScript to run the instructions inside its braces.
Give Your Function Information
Functions become more useful when they can work with different values. A parameter is a named input declared in a function. An argument is the actual value you pass when calling it.
function greet(name: string): void {
console.log("Hello, " + name + "!");
}
greet("Alex");
greet("Jordan");
The parameter name: string tells TypeScript that the function expects text. The values "Alex" and "Jordan" are arguments.
greet(42); // Type error: number is not string
TypeScript can detect that mismatch before the function executes.
Accept More Than One Value
A function can accept multiple parameters, separated by commas. Each parameter can have its own type.
function showPlayer(
name: string,
score: number
): void {
console.log(name + " scored " + score);
}
showPlayer("Alex", 100);
showPlayer("Jordan", 85);
The order of arguments matters. TypeScript checks each argument against the corresponding parameter.
showPlayer(100, "Alex") work? No — the first parameter expects a string and the second expects a number.Let Your Function Give Something Back
Some functions simply perform an action. Others calculate or create a value and return it to the code that called them.
function add(
first: number,
second: number
): number {
return first + second;
}
const total: number = add(10, 5);
console.log(total);
The : number after the parentheses describes the function’s return type. The return statement sends the calculated value back to the caller.
TypeScript can also infer return types, but writing them explicitly is often useful when learning or documenting a function’s intended behavior.
Not Every Function Returns a Result
When a function doesn’t return a meaningful value, you can describe its return type as void.
function announce(message: string): void {
console.log("Announcement: " + message);
}
announce("Welcome to TypeScript!");
Printing to the console is an action, not the same as returning a value. Compare console.log(message), which displays information, with return message, which sends information back to the caller.
A Shorter Way to Write Functions
TypeScript also supports arrow functions, which use the => symbol. They’re common in modern JavaScript and TypeScript.
const double = (value: number): number => {
return value * 2;
};
console.log(double(5));
For a short expression, an arrow function can use an implicit return:
const triple = (value: number): number =>
value * 3;
console.log(triple(4)); // 12
this differently. We’ll revisit that when learning about classes.Make Functions More Flexible
Sometimes an argument should be optional. Add ? after a parameter name to indicate that callers may omit it.
function welcome(name?: string): void {
if (name) {
console.log("Welcome, " + name + "!");
} else {
console.log("Welcome, developer!");
}
}
welcome("Alex");
welcome();
An optional parameter may be undefined, so your function should account for the missing value.
Alternatively, provide a default value:
function greet(
name: string = "developer"
): string {
return "Hello, " + name + "!";
}
console.log(greet());
console.log(greet("Alex"));
Protect Your Function’s Inputs and Outputs
TypeScript doesn’t just check variables. It also checks function arguments and returned values.
function getScore(): number {
return "one hundred"; // Type error!
}
This function promises to return a number but actually returns a string. TypeScript reports the conflict.
function getScore(): number {
return 100;
}
console.log(getScore()); // 100
Build a Reusable Greeting Generator
Let’s combine typed parameters, return values, and function calls into a useful example.
function createGreeting(
name: string,
language: string
): string {
return `Hello, ${name}! Enjoy learning ${language}!`;
}
const greeting = createGreeting(
"Alex",
"TypeScript"
);
console.log(greeting);
One function can create greetings for any developer and any programming language. You simply provide different arguments.
Create a Personalized Greeting Generator
Build a reusable TypeScript function that welcomes developers and celebrates their progress.
Your Mission
- Change the name and programming language passed to
createGreeting(). - Update the function’s returned message to include your own greeting.
- Change the
lessonsCompletedargument to a different number. - Use
console.log()to display the returned greeting. - Call the function again with another developer’s details.
- Run the code and verify both greetings appear.
lessonsCompleted. Read the TypeScript error, then correct the argument and run the code again.Make Your Functions Come Alive!
Edit the function, customize its arguments, and run your code. The sandbox checks TypeScript types, compiles the program, and displays console output.
Preparing TypeScript sandbox…
What You’ve Learned
You’re Building Reusable TypeScript Code!
You can now:
- Declare and call TypeScript functions.
- Distinguish parameters from arguments.
- Add types to function parameters.
- Return values using
return. - Describe return types with
string,number, orvoid. - Write arrow functions.
- Use optional and default parameters.
- Recognize and correct function type errors.
Next up: Loops — learn how to repeat instructions efficiently using for, while, and other looping techniques!
Your Learning Journey
0 / 11 CompletedKeep going! Every completed lesson brings you closer to building reliable applications with TypeScript.
Fantastic Work!
You’ve learned how to create reusable TypeScript functions, work with typed parameters, return values, and write arrow functions. You’re building the skills to organize code into clear, dependable pieces!
