JIYIK CN >

Current Location:Home > Learning > PROGRAM > TypeScript >

Function return types in TypeScript

Author:JIYIK Last Updated:2025/04/15 Views:

TypeScript is a strongly typed language and it is always encouraged to define the types correctly for all variables used in TypeScript. These types can help in development later, especially during debugging.

In addition to variables, functions can also have a return type. Usually, when the type is not defined, the compiler automatically infers the type based on the type of the variable returned.

However, this is inconvenient and may result in less strict types like anyor even as return type, so it is better to return the type to a TypeScript function.undefined

returnUsing types for statements in TypeScript functions

If no type is mentioned, the TypeScript compiler automatically infers the return type. It is a good idea to add types to your functions to ensure that the correct types are passed through your application code.

Here's how to add types to a TypeScript function.

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

console.log(addTwoNumbers(5,6));

Output:

11

So numberthe type has been added addTwoNumbersto the end of , so it indicates that addTwoNumbersthe return type of the function is numberof type . TypeScript supports unions and complex types as return types of functions.

The following example shows an example of type union as the return type of a function.

function conditionalAdd(a : number, b : number ) : number | string {
    if ( a + b > 20){
        return "more than 20!";
    } else {
        return a + b;
    }
}

console.log(conditionalAdd(3,21));

Output:

"more than 20!"

You can even use an interface as the return type of a function. Suppose you have a function that returns all configuration information.

It can be achieved as follows.

interface Config {
    logLevel : string,
    cache : boolean,
    dbUrl : string,
    password : string,
    production : boolean,
    version : number
}


function getConfig() : Config {
    return {
        logLevel : "debug",
        cache : true,
        dbUrl : "localhost:5432",
        password : "postgres",
        production : false,
        version : 2
    }
}

The benefit of using this approach is that you can return objects directly without declaring variables and get suggestions during development.

ReturnTypeGet the return type of a function in TypeScript using type

ReturnTypeTypes is useful to understand the type of a function which may or may not be written by a user as it may be in a third-party library. The following code snippet shows ReturnTypehow types can detect the return type.

function findStudentWithRoll(roll : number){
    const students : Student[] = [
        {
            name : 'Tintin',
            roll : 1,
            passed : true
        },
        {
            name : 'Haddock',
            roll : 2,
            passed : false
        },
        {
            name : 'Calculus',
            roll : 3,
            passed : true
        },
    ];
    return students.find( student => student.roll === roll) || null;
}


const studentRoll_1 : ReturnType<typeof findStudentWithRoll> = findStudentWithRoll(1);
if ( studentRoll_1 !== null){
    console.log(studentRoll_1);
}

Output:

 {
  "name": "Tintin",
  "roll": 1,
  "passed": true
}

Hence, ReturnType<typeof findStudentWithRoll>it is convenient to return <int> Student | nullfor further use in writing application logic.

Previous: None

Next:exclude attribute in TypeScript

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Handling exceptions with try..catch..finally in TypeScript

Publish Date:2025/04/15 Views:170 Category:TypeScript

This article will discuss try..catch..finally handling exceptions in TypeScript using the statement. Handling exceptions in TypeScript In TypeScript, try..catch..finally a block handles exceptions that occur during program runtime. It allow

Convert JSON object to a class in TypeScript

Publish Date:2025/04/15 Views:80 Category:TypeScript

Data on the internet flows in the form of strings, which can be converted into a very popular format called JSON. The JSON representation of this data usually represents an object or even a class in TypeScript. TypeScript provides the abili

Update TypeScript to the latest version using NPM

Publish Date:2025/04/15 Views:119 Category:TypeScript

This article provides a guide to update to the latest version of TypeScript using npm, which is the best and most popular method used by developers. This also gives us an in-depth look at what npm is and why to use it. Node Package Manager

Using jQuery and TypeScript

Publish Date:2025/04/15 Views:148 Category:TypeScript

This article provides the basic understanding and concepts of using jQuery with TypeScript. It guides on how to use jQuery in TypeScript through a coding example and outputs using various methods in TypeScript and provides knowledge about w

Checking for undefined in TypeScript

Publish Date:2025/04/15 Views:196 Category:TypeScript

This article will demonstrate how programmers can check for undefined in TypeScript using various coding examples and situations. It not only gives you an understanding of checking for undefined in TypeScript, but also helps in differentiat

exclude attribute in TypeScript

Publish Date:2025/04/15 Views:190 Category:TypeScript

This article will discuss excluding properties from a TypeScript type. The exclude property is used to create another type from an existing type with fewer or modified properties. Omit Exclude properties from types in TypeScript TypeScript

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial