FEWV minutes of TypeScript Functions
» Functions Declaration
-
Functions in TypeScript are similar to those in JavaScript, but with the added benefit of type-checking and optional parameters.
-
Function Declaration: So in JavaScript, we type functions like this:
function greet(name) {
console.log(`Hello ${name}!`);
}
greet("John");
-
But here we do not know what value type the developer intended here for the parameter name, typing this in TypeScript, will throw an error because the name has implicitly any type, and in TypeScript, this is not allowed.
-
So the same function can be typed like this to avoid TypeScript, shouting us with error.
function greet(name: string) {
console.log(`Hello ${name}!`);
}
greet("John");
- Now here it is clear that the parameter name has a string type, so our output will also have a string type, and now if we try to type any other type for example a number or a boolean value, TypeScript will throw an error.
- This is how we declare functions in TypeScript.
» Required Parameters
- In JavaScript, a function can be called with any number of arguments but in TS, it is necessary to declare all parameters if we don’t want TS to throw us another error.
function greet(firstName: string, lastName: string) {
console.log(`Hello ${firstName} ${lastName}`);
}
greet("John");
// Error: Expected 2 arguments, but got 1.
greet("John", "Doe"); // Ok
» Optional Parameters
- TypeScript also supports optional parameters in functions, which are denoted with a ? after the parameter name. For example:
function greet(name: string, age?: number) {
if (age) {
console.log(`Hello, ${name}, your are ${age} years old!`);
} else {
console.log(`Hello, ${name}!`);
}
}
greet("John"); // Output: "Hello, John!"
greet("Jane", 25); // Output: "Hello, Jane, you are 25 years old!"
- These optional parameters are implicitly able to be undefined. But parameters that aren’t marked as optional with a ? must always be provided.
» Default Parameters
- TypeScript also allows us to specify default values for parameters using the (=) symbol. For example:
function greet(name: string, age: number = 30) {
console.log(`Hello, ${name}, you are ${age} years old!`);
}
greet("John"); //valid
greet("Jane", 25); //valid
Console
Hello, John, you are 30 years old!
Hello, Jane, you are 25 years old!
- Here we said that parameter age has a default value of 30 but if the age is provided like in case of Jane, use that age.
» Function Return Types
-
TypeScript functions can also have a return type annotation that specifies the expected return type of the function.
-
That means the type of the value returned by the function can be explicitly defined.
function add(x: number, y: number): number {
return x + y;
}
console.log(add(2, 3));
Console
5
- TypeScript understands all the possible values returned by a function, it’ll know what type the function returns. If a function contains multiple return statements with different values, TypeScript will infer the return type to be a union of all the possible returned types.
» More return types
-
In TypeScript, a function can have a return type of void or never.
-
A function with a return type of void means that the function does not return any value. For example:
function greet(): void {
console.log("Hello");
}
-
Here,greet() does not return anything but logs a message to the console, just for understanding.
-
On the other hand, a function with a return type of never means that the function never returns, either because it throws an exception or because it enters into an infinite loop. For example:
function throwError(message: string): never {
throw new Error("Something went wrong");
}
- Never and void are not the same, void is for a function that will return nothing but never is for a function that will never return.
» Rest Parameters
-
Rest parameters are just like other parameters, but here the type of a parameter must always be an array.
-
The rest parameter must be the last parameter of a function, and there can only be one rest parameter per function.
-
In TypeScript, the rest parameter syntax allows a function to accept a number of arguments as an array. This is achieved by declaring the last parameter of a function with the spread operator (…) and [] syntax to indicate it’s an array with a number of arguments.
function sum(a: number, ...numbers: number[]): number {
return a + numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum(1, 2, 3, 4));
console.log(sum(5, 10));
}
Console
10
15
I hope this cleared - Functions in TypeScript and its various parameters. Thank You!!😊