DEV Community

Cover image for How to write functions in TypeScript
Aneeqa Khan
Aneeqa Khan

Posted on

5

How to write functions in TypeScript

Hello, today I want to share my knowledge regarding functions in typescript.

Functions in plain javascript

In javascript, we usually create a function like this

function greetings(name, count) {
  return "I am a basic javascript greetings function";
}
Enter fullscreen mode Exit fullscreen mode

Here name and count are 2 params passed to this function but it doesn't know the types of the passed params.
And in javascript all parameters are optional so if you don't pass any of these params to your function it won't give you an error. Also if you pass more than 2 params to the above function it still won't give any error.

Functions in typescript

So we can improve our functions to understand the code and debug the errors with typescript.

function greetings(name: string, count?: number): string {
  return "I am a better javascript greetings function";
}
Enter fullscreen mode Exit fullscreen mode

Here we defined our params types with string and number. It means name param will always be string and count param will always be number.
Other than that name param is mandatory and the ? beside a count param defines it as an optional parameter here.
So it means if you do not give name a param to the above function it will give an error also if you pass more than 2 params to the above function it will again give an error.

And the : string word after the function brackets represents that greetings function will return output in string type.

So here we learned these things about functions

  • Function params types
  • All params are mandatory in typescript function
  • However, we can define optional params with ? sign
  • Function return type

Default initialized Parameters

We can also initialize our params with default values and it gives us the flexibility to call our function with no params.

function greetings(name: string = 'Human'): string {
  return `Hello ${name}`;
}
greetings(); //Hello Human
greetings('Ben'); //Hello Ben
Enter fullscreen mode Exit fullscreen mode

Arrow functions in typescript

Now I'll convert above greetings function into an arrow function.

const greetings = (name: string = 'Human'): string => {
  return `Hello ${name}`;
}
Enter fullscreen mode Exit fullscreen mode

if your function is a one-liner then you can write it like this too

const greetings = (name: string = 'Human'): string => return `Hello ${name}`;

Enter fullscreen mode Exit fullscreen mode

Function's type

A function's type consists of the types of its argument and its return type. For example here

let logOutput: (value: string) => void;
Enter fullscreen mode Exit fullscreen mode

logOutput parameter's type must be "function that accepts a string and returns type void".

We can use it like this

const logMessage = (message: string): void => console.log(message);
const logError = (err: string): void => console.error(err);
Enter fullscreen mode Exit fullscreen mode

here both functions take string parameter and return void type or you can say does not have return block. Now we use logOutput like this

if(value === '') {
  logOutput = logError;
} else {
  logOutput = logMessage;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

  • Typescript functions are easier to use and easy to read.
  • Flexibility is included just like you can define optional params to a function.
  • Clean syntax with arrow functions in typescript

Feel free to connect on Twitter

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (2)

Collapse
 
aviavinav profile image
Avi Avinav

Amazing article!

Collapse
 
nawabanjum profile image
Muhammad Nawab Anjum

informative.
I think one type of function you have missed, How to pass a more than one parameters with only one single trick.

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay