EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials TypeScript Tutorial TypeScript Functions
Secondary Sidebar
TypeScript Tutorial
  • Function Of Array
    • TypeScript Function Interface
    • TypeScript Functions
    • TypeScript Export Function
    • TypeScript function return type
  • TypeScript Basic and Advanced
    • What is TypeScript?
    • Typescript Examples
    • TypeScript Versions
    • TypeScript Operators
    • JavaScript dump object
    • JavaScript get Method
    • Webpack ReactJS
    • Code Generator JavaScript
    • JavaScript Projects
    • Call Stack JavaScript
    • JavaScript Projects GitHub
    • JavaScript Filter Function
    • JavaScript nan
    • JavaScripttimestamp
    • TypeScript loop
    • CoffeeScript
    • TypeScript Webpack
    • setTimeout TypeScript
    • DHTMLX
    • CoffeeScript for loop
    • TypeScript number
    • JavaScript export module
    • TypeScript string contains
    • TypeScript Inheritance
    • TypeScript get
    • TypeScript undefined
    • TypeScript Global Variable
    • TypeScript Dictionary
    • TypeScript Generic
    • TypeScript Cast Object
    • TypeScript Optional Parameters
    • TypeScript? switch
    • TypeScript promise
    • TypeScript tuple
    • TypeScript Hashmap
    • TypeScript let
    • TypeScript Getter
    • TypeScript Pattern Matching
    • TypeScript number to string
    • TypeScript substring
    • TypeScript?lambda
    • TypeScript UUID
    • TypeScript JSDoc
    • TypeScript Decorators
    • Typescript for loop
    • TypeScript HTTP Request
    • TypeScript Abstract Class
    • TypeScript Question Mark
    • TypeScript Nullable
    • TypeScript reduce
    • TypeScript Mixins
    • TypeScript keyof
    • TypeScript string to number
    • TypeScript JSON parse
    • TypeScript const
    • TypeScript declare module
    • TypeScript String
    • TypeScript filter
    • TypeScript Multiple Constructors
    • TypeScript? Set
    • TypeScript string interpolation
    • TypeScript instanceof
    • TypeScript JSON
    • TypeScript Arrow Function
    • TypeScript generator
    • TypeScript namespace
    • TypeScript default parameter
    • TypeScript cast
    • TypeScript babel
    • Typescript Key-Value Pair
    • TypeScript if
    • TypeScript keyof Enum
    • TypeScript wait
    • TypeScript Optional Chaining
    • TypeScript JSX
    • TypeScript Version Check
    • TypeScript Unit Testing
    • TypeScript Handbook
    • TypeScript module
    • TypeScript Extend Interface
    • TypeScript npm
    • TypeScript pick
    • TypeScript Interface Default Value
    • JavaScript import module
    • Obfuscate Javascript
    • TypeScript basics
    • setInterval TypeScript
  • Type of Union
    • TypeScript Object Type
    • TypeScript type check
    • TypeScript promise type
    • TypeScript JSON type
    • TypeScript Union Types
    • TypeScript typeof
    • TypeScript Types
  • TypeScript Array
    • TypeScript Array of Objects
    • Methods TypeScript Array
    • TypeScript remove item from array
    • TypeScript add to array
    • TypeScript Array Contains

TypeScript Functions

By Priya PedamkarPriya Pedamkar

TypeScript Functions

Introduction to TypeScript Functions

Any programming language has its own set of predefined functions. And some functions are going to be defined by us. Functions are the main building blocks of any programming paradigm. If you know JavaScript functions then it is a lot easier to know about typescript functions. Typescript is a superset of JavaScript and for typescript, you need to be familiar with its ES6 syntax.

How to Define TypeScript Functions?

There are two types of functions named and anonymous which do not have any name.

Syntax:

function add(a,b) {
return a*b;
}

We will also see the same example for anonymous functions.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,818 ratings)
Const add = (a,b)=> a*b

But now, you may say that, what are the advantages we have in typescript over JavaScript then? Well, one of the core features is that typescript as the name suggests is the type. Yes, you can give type to the function also.

Example:

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

How to Call TypeScript Functions?

If you are writing any function, then it has to be called to execute it. Writing function is known as a function definition in programming. We are calling the function with the function name and a pair of parenthesis.

For example, let’s take the above add function. We will call that function as below.

add(5,10); // we are providing values for the given parameters.

How to Return TypeScript Functions?

In this example you can see there are many situations where we have used return keyword is just to return value from it. We can return any type of value. If you want to return something from a function at that time you must use return statement with the semicolon. We can only return one and only one value from a single function. While returning the value we must check that returning value and type function should be the same so that the caller get the return value.

Example:

function cake():string {
//function defination
//the function returns a string
return "Welcome to the world of cakes"
}
function bake() {
var bakery = cake();
console.log(bakery);
}
bake()

Look at the above example carefully, here we have two functions one is bake and the other is cake. We are calling function cake inside the function bake. And function cake returning the string value. In the bake function, we are assigning our functional call to the variable bakery. Then we log that variable to the console. Upon executing this we will get “Welcome to the world of cakes ” as an output. It is easy to understand with little practice.

What is Parameterized TypeScript Functions?

The parameter is the case where a user has to give some value to work on. The parameter has to be considered important if mentioned. We must have to give respective values to each parameter in typescript. In programming, while working with parameterized functions no arguments should be matched with no of arguments.

Example:

function student(fName: string, lName: string) {
return fName + " " + lName;
}
let student1= student ("John", "roy");

Here, one important note to understand is that what if we do not give all arguments. or the case where we are not having data to give value for that parameter, in this situation, we have the concept of the optional parameter in typescript. These optional parameters use to show as this is optional.

We will look at the example. Take the same function student and we will try to make some parameters optional.

Example:

function student(fName: string, lName?: string) {
return fName + " " + lName;
}
let student1= student ("John");

In above example we just gave value for first name parameter. And it will work without the second parameter. Now it will not show any error.

Now, other than this if we wanted to give some default value to the parameter then we can do that.

Example:

function student(fName: string, lName: string = “rey”) {
return fName + " " + lName;
}
let student1= student ("John");

Now, the above program will work correctly without any errors. It is fine to give a default value to the parameter.

Examples of TypeScript Functions

Following are the examples as given below:

Example #1

fat arrow function:

const msg = ()=>”Welcome to the typescript demo”;

Here in the above example, we used an arrow function. Note that here we are not using the return statement because as per the convention if we have only one statement and i.e return statement then we don’t need to write it explicitly. This is shorthand syntax and is most commonly used in typescript.

Example #2

We can call one function as many times as we want, look at the below example to know more.

function student(fName: string, lName?:string) {
return fName + " " + lName;
}
student ("John");
student ("sam");
student ("ken");
student ("bren");

And simultaneously we made last name parameter optional. So that we don’t need to give the second parameter.

Example #3

Another example we are going to look for rest parameters. Till now we have seen parameters like optional, default and required. But there is one more case to this. What if we don’t know how much parameters the function will exactly take.

We will make use of the ellipsis (…) operator here. Again we will take the above example of a student.

function student(fName: string, …remainigStudents: string [] ) {
return fName + " " + remainigStudents.join(“ ”);
}
let allStudents = student(“john”, ”sam”, ”reema”, ”kerry”, “jem”);

If you look closely we have given n no of arguments. But in a function definition, we just gave two parameters. But look at that three dots(…0) before the second parameter. It is called ellipsis. Which helps us do so.

Writing functions and work on them needs some debugging skills. For working with functions you need to understand the ES6 features of JavaScript.

Conclusion

Working with functions is the most important thing because by combining these functions we are designing the functionality. Functions in typescript are referred to as ES6 syntax. This is mostly seen with the arrow functions. ES6 is an ECMASript standard for JavaScript. We also have ES7 now and more releases will come in the future with some new features.

Recommended Articles

This is a guide to TypeScript Functions. Here we discuss the Introduction and how to call and define typescript functions along with different examples. You may also look at the following articles to learn more –

  1. TypeScript Types
  2. TypeScript vs CoffeeScript
  3. TypeScript Array
  4. TypeScript Versions
Popular Course in this category
JavaScript Training Program (39 Courses, 24 Projects, 4 Quizzes)
  39 Online Courses |  24 Hands-on Projects |  230+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more