Open In App

TypeScript Function

TypeScript Functions are the most crucial aspect of TypeScript as it is a functional programming language. Functions are pieces of code that execute specified tasks. They are used to implement object-oriented programming principles like classes, objects, polymorphism, and abstraction. It is used to ensure the reusability and maintainability of the program.

Syntax:

function functionName(arg: argType) {
    //function Body
}

Where:



TypeScript Function Types

Example 1:






// Parameter type annotation
function greet(name: string) {
    console.log("Hello, " + name + "!!");
}
greet("GeeksforGeeks")

Output:

Example 2:




// Return type annotation
function greet(): string {
    return ("Hello, GeeksforGeeks!!");
}
console.log(greet())

Output:

Example 3:




async function greet(): Promise<string> {
    return ("Hello, GeeksforGeeks!!");
}
greet().then(
    (result) => {
        console.log(result)
    }
)

Output:

Example 4:




// Anonymous Function
let myFunction = function (a: number, b: number): number {
    return a + b;
};
  
// Anonymous Function Call
console.log(myFunction(7, 5));

Output:

Conclusion: In this article we have seen the functions in typescript that whar are the types of fucntion with code examples. It makes easy to deal with the code and helps in code reusability and readability.


Article Tags :