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";
}

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";
}

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

Arrow functions in typescript

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

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

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

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

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;

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);

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;
}

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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why Did We Choose Web Components?

Everything about OOP in TypeScript 4.5

Clearer RxJava intentions with Single and Completable

Learn Deno: Chat app

How To Import CSV File In MySQL Using Node.js

Bootstrap DateTimePicker Example

Week 2 Javascript

Distributed Transaction — Implementation using REDIS and NodeJS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aneeqa Khan

Aneeqa Khan

More from Medium

How to build awesome UI’s in a few hours with React & MUI V.5 ⚛️🎨

Understanding Local State with React Hooks

Improve performance of React App with lazy loading and preloading images

Build dynamic breadcrumb routes and child routes with matchPath in React Router v6