TS PlaygroundLearnJavaScriptFunctions
javascript/beginner

Functions

Write typed functions with parameters and return types.


Functions in TypeScript

TypeScript lets you annotate both parameter types and the return type.

Basic function

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

Arrow functions

const multiply = (a: number, b: number): number => a * b;

TypeScript will warn you if you pass the wrong types or return the wrong value.

Optional parameters

Add ? to make a parameter optional:

function greet(name?: string): string {
  return `Hello, ${name ?? 'stranger'}!`;
}

Your task

Write and export a function named add that:

  • Takes two number parameters: a and b
  • Returns their sum as a number
export function add(a: number, b: number): number {
  // your code here
}
// Write and export a function named 'add'
// that takes two numbers and returns their sum

Click Run Tests to see results
VariablesTypes & Interfaces