Language: EN

retorno-de-funciones-en-typescript

What are and how to use function returns in TypeScript

In programming, a function can return a value after executing its code block. This value is called the “return” of the function.

In TypeScript, you can specify the return type of a function to ensure that the function returns the expected data type. This helps prevent errors and improves code readability.

If you want to learn more about Function Returns
check out the Introduction to Programming Course read more

The basic syntax for defining a function with a return type in TypeScript is as follows:

function functionName(parameters): returnType {
    // function body
    return value;
}

For example, a function that adds two numbers and returns the result as a number (number):

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

In this case, number is the return type of the add function.

Primitive Return Types

TypeScript allows you to specify primitive return types (such as number, string, boolean, etc).

Here are some examples:

function getName(): string {
    return "Luis";
}

function isAdult(age: number): boolean {
    return age >= 18;
}

Complex Return Types

In addition to primitive types, functions in TypeScript can also return complex types (such as objects, arrays, or tuples).

This is very useful as an alternative to return multiple return values. Since we can only return a single value, we can return any grouping of values.

Objects

function createPerson(name: string, age: number): { name: string; age: number } {
    return { name, age };
}

const person = createPerson("Ana", 25);
console.log(person); // { name: 'Ana', age: 25 }

Arrays

function getNumbers(): number[] {
    return [1, 2, 3, 4, 5];
}

const numbers = getNumbers();
console.log(numbers); // [1, 2, 3, 4, 5]

Custom Types

TypeScript also allows returning custom types, such as those created using type or interface.

type Person = {
    name: string;
    age: number;
};

function createPerson(name: string, age: number): Person {
    return { name, age };
}

const person = createPerson("Carlos", 30);
console.log(person); // { name: 'Carlos', age: 30 }

Functions that do not return values

In TypeScript, if a function does not return any value, the void type is used as the return type. This is useful for functions that only perform actions and do not need to return a value.

function greet(name: string): void {
    console.log(`Hello, ${name}`);
}

greet("María"); // Hello, María

Optional Returns

Sometimes, a function can optionally return a value. That is, it can return a value or undefined. In these cases, a type union can be used.

function findElement(arr: number[], value: number): number | undefined {
    return arr.find((el) => el === value);
}

const result = findElement([1, 2, 3], 2);
console.log(result); // 2

const nonexistentResult = findElement([1, 2, 3], 4);
console.log(nonexistentResult); // undefined