Specifying Types for Functions in TypeScript
3 min read
Before Getting Started
While serving as a software development specialist in the Air Force, I was assigned to a new project as a full-stack developer due to increased demand. This led me to work extensively with TypeScript (react).
Actually, I kind of have a love-hate relationship with loosely-typed languages, which is one of the reasons I don’t particularly enjoy front-end development.
How to Declare a Function
JavaScript has several ways to declare functions.
Named Function Declaration
function hello {
// ...
}
Anonymous function expression
An unnamed function; the JavaScript engine assigns the name of the variable.
const hello = function () {
// ...
}
Arrow function
const hello = () => {
// ...
}
In this post, I will focus on explaining with the arrow function, which is widely used nowadays (the one I use the most).
Call Signature
Now, let’s take a look at how to specify types for functions.
How to specify types for basic function arguments
const sum = (a: number, b: number): number => {
return a + b;
};
// a: number
// b: number
// return: number
How to specify types using interfaces
interface sumInterface {
(a: number, b: number): number
}
const sum: sumInterface = (a, b) => {
return a + b
}
How to declare types for optional parameters
To make parameters optional instead of passing all of them, you can add a ? to make them optional.
const sum = (a: number, b?: number) => {
return a + b
}
sum(10, 10)
sum(10)
The use of the ? keyword is equivalent to adding | undefined: const sum = (a: number, b: number | undefined) => (a + b)
Additionally, if b receives an undefined value, you can handle the undefined case using || or ??.
const sum = (a: number, b: number) => {
return a + (b || 0)
}
Alternatively, you can initialize the parameter with a default value if no value is provided. In this case, TypeScript's type inference will deduce the type of the argument, so you don’t need to explicitly declare the type.
const sum = (a: number, b = 0) => {
return a + b
}
sum(10) // 10
sum(10, 20) // 30
sum (10, undefined) // 10
Named Parameters
When using named parameters, you can declare the parameters inside {} and then specify the type after that. Here’s how it works:
const greet = ({ name, age }: { name: string, age: number })=> {
console.log(`Hello, my name is ${name} and I am ${age} years old.`);
}
greet({ name: 'Alice', age: 30 });
In the case of a traditional function with a small number of parameters, you might not use named parameters often. However, when making API calls, it is very convenient to use named parameters for the body, and that’s where I often use this approach.
const greet = async ({ name, age }: { name: string, age: number }) => {
const response = await fetch("/api/greet", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name, age })
});
const responseData = await response.json();
console.log(responseData);
}
greet({ name: 'Alice', age: 30 });
Using Interfaces
Using an interface with named parameters can help keep the code cleaner.
interface GreetParams {
name: string;
age: number;
}
const greet = async (requst: GreetParams) => {
const response = await fetch("/api/greet", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requst)
});
const responseData = await response.json();
console.log(responseData);
}
greet({ name: 'Alice', age: 30 });
Callback Function
In the case of a callback function, you can specify the type like
name: (param: paramType) => returnType
const processData = (data: number[], callback: (item: number) => number):
number[] => {
return data.map(callback);
};
const double = (num: number): number => {
return num * 2;
};
const numbers = [1, 2, 3, 4];
const doubledNumbers = processData(numbers, double);
console.log(doubledNumbers); // [2, 4, 6, 8]