Sling Academy
Home/TypeScript/Function Parameters Annotations in TypeScript: A Practical Guide

Function Parameters Annotations in TypeScript: A Practical Guide

Last updated: January 07, 2024

Introduction

Adding static types to JavaScript, TypeScript brings clarity and predictability to codebases. Function parameter annotations are a cornerstone of TypeScript, offering precise control over the types of arguments functions can accept.

Basic Annotations

Befriending TypeScript starts with understanding basic type annotations. Let’s say you have a function that sums two numbers. In JavaScript, you would write:

function sum(a, b) {
  return a + b;
}

In TypeScript, you can explicitly specify the types of parameters a and b to be numbers:

function sum(a: number, b: number): number {
  return a + b;
}

This ensures that only numbers are passed to the sum function.

Advanced Types

When you need more than just primitives, TypeScript type annotations shine. If you’re working with an object, for example:

function greet(person: { name: string; age: number }) {
  return 'Hello ' + person.name;
}

This defines a parameter person that must be an object with a name property of type string and an age property of type number.

Interface Parameter Annotations

As your applications grow, you’ll want to extract types out for reusability with interfaces:

interface Person {
  name: string;
  age: number;
}

function greet(person: Person) {
  return 'Hello ' + person.name;
}

Now Person can be reused across multiple functions, promoting DRY code.

Optional Parameters and Defaults

Optional parameters in TypeScript can be denoted with a ?:

function greet(name: string, age?: number) {
  return 'Hello ' + name;
}

If age is left out, TypeScript will infer it as number | undefined. To set default values:

function greet(name: string, age: number = 30) {
  return 'Hello ' + name;
}

This sets a default age if none is provided.

Rest Parameters and Tuples

TypeScript also supports rest parameters and their annotation, excellent for when the number of parameters is unknown:

function sum(...numbers: number[]): number {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

For a fixed sequence of parameters, you can use tuple types:

function trainModel(...dataset: [number, number, string][]) {
  // Implementation goes here.
}

This makes sure the arguments follow a specific structure.

Function Overloads

In more sophisticated scenarios, your functions might need to handle different types with function overloads:

function getValue(key: string): string;
function getValue(key: number): number;
function getValue(key: any): any {
  // Implementation varies based on key
}

TypeScript will ensure you’re handling all declared scenarios within your function body.

Generic Parameter Types

When you need maximum flexibility with type-safety, generics come into play:

function insertAtBeginning<T>(array: T[], value: T) {
  return [value, ...array];
}

Generics allow you to define a placeholder type T, which can be used to enforce consistency across the parameters.

Conclusion

TypeScript’s function parameter annotations arm developers with precision and power, significantly boosting code reliability and maintainability. Embracing them is a major step towards type-safe JavaScript applications.

Next Article: Mastering Function with Default Parameters in TypeScript

Previous Article: Multidimensional Array in TypeScript: A Complete Guide

Series: The First Steps to TypeScript

TypeScript

You May Also Like

  • TypeScript: setInterval() and clearInterval() methods (3 examples)
  • TypeScript sessionStorage: CRUD example
  • Using setTimeout() method with TypeScript (practical examples)
  • Working with window.navigator object in TypeScript
  • TypeScript: Scrolling to a specific location
  • How to resize the current window in TypeScript
  • TypeScript: Checking if an element is a descendant of another element
  • TypeScript: Get the first/last child node of an element
  • TypeScript window.getComputerStyle() method (with examples)
  • Using element.classList.toggle() method in TypeScript (with examples)
  • TypeScript element.classList.remove() method (with examples)
  • TypeScript: Adding Multiple Classes to An Element
  • element.insertAdjacentHTML() method in TypeScript
  • TypeScript – element.innerHTML and element.textContent
  • Using element.removeAttribute() method in TypeScript
  • Working with Document.createElement() in TypeScript
  • Using getElementById() method in TypeScript
  • Using Window prompt() method with TypeScript
  • TypeScript – window.performance.measure() method (with examples)