By Hemanta Sundaray on 2023-04-11
Welcome to the beginner's guide to TypeScript functions! In this guide, we will explore different ways to add type annotations to function parameters, as well as how to explicitly specify return types for functions.
Let’s get started!
In TypeScript, we can give type annotations to function parameters by placing a colon (:) next to the parameter name. The type annotation ensures that the parameters are of the correct type.
function greeting(name: string) {
console.log(`Hello ${name}!`)
}
greeting("World") // Prints: Hello World!
greeting(12) // Error: Argument of type 'number' is not assignable to parameter of type 'string'.
In the example above, we used a named function (also called a function declaration). The name of the function is greeting. But named functions are not the only way we can define functions in JavaScript and TypeScript. We can also use function expressions and arrow functions as shown below:
// Function expression
const greeting = function (name: string) {
console.log(`Hello ${name}!`)
}
greeting("World") // Prints: Hello World!
greeting(12) // Error: Argument of type 'number' is not assignable to type 'string'.
// Arrow function
const greeting2 = (name: string) => {
console.log(`Hello ${name}!`)
}
greeting2("World") //Prints: Hello World!
greeting2(12) // Error: Argument of type 'number' is not assignable to type 'string'.
We can indicate that a parameter is optional by placing a ? after its name (before the colon), as shown below. This tells TypeScript that the parameter doesn’t always have to be provided.
function greeting(name?: string) {
console.log(`Hello ${name || "Stranger"}!`)
}
greeting() // Prints: Hello Stranger!
If a parameter is assigned a default value, TypeScript will infer the variable type to be the same as the default value’s type.
function greeting(name = "Stranger") {
console.log(`Hello ${name}!`)
}
greeting() // Prints: Hello Stranger
In TypeScript, we can explicitly specify what type a function returns by adding a colon (:) followed by the type annotation after the closing parentheses of the function definition.
function greeting(name: string): string {
return `Hello, ${name}!`
}
We can also explicitly specify return types of arrow functions, as shown below:
const greeting = (name: string): string => {
return `Hello, ${name}!`
}
It is often preferred to use type annotations for functions, even when those functions don’t return anything. Example:
function greeting(name: string) {
console.log(`Hello, ${name}!`)
}
The function greeting simply logs a greeting to the console. There is no returned value, so we must treat the return type as void. A proper type annotation for this function would look like this:
function greeting(name: string): void {
console.log(`Hello, ${name}!`)
}