CodeBlanks Logo Icon CodeBlanks

Function declaration

Learn to define functions with types.

Function declaration

In TypeScript, a function is defined with parameter types and a return type. This provides type safety both at the call site and inside the function body.

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

Parameter types go inside the parentheses, the return type goes after them.

Calling a typed function

When calling a typed function, TypeScript checks that the arguments match the parameter types. A wrong type causes a compile error.

function topla(a: number, b: number): number {
  return a + b;
}
topla(3, "metin");  // error: string not number

Type checking prevents incorrect use of the function.

Practice Write a typed function

Define a function named topla with a and b parameters of type number and return type number. The function should return a + b. Print the result of calling topla(4, 5) with console.log.

Starter code

index.ts
// topla adında bir fonksiyon tanımla
// a ve b parametreleri number, dönüş türü number olsun
// a + b değerini döndür
// topla(4, 5) sonucunu yazdır

Sample solution

index.ts
function topla(a: number, b: number): number {
    return a + b;
}
console.log(topla(4, 5));

Expected output

9

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 In <code>function carp(x: number, y: number): number</code>, what does <code>: number</code> after the parameter list specify?

  • The parameter type
  • The function name
  • A variable declaration
  • The return type Correct answer

Explanation: The <code>: number</code> after the parameter list's closing parenthesis specifies the type of the value the function returns.

2 Add the return type

Question
function kare(x: number): ____ { return x * x; }
Answer
function kare(x: number): number { return x * x; }

Explanation: <code>x * x</code> returns a number, so the return type must be <code>number</code>. <code>string</code>, <code>void</code> and <code>boolean</code> are wrong types for a number.

3 Function declaration concepts

Term Meaning
function f(): void Function returning no value
function f(a: number) Function with number parameter
function f(): string Function returning a string
Function declaration Typed function definition

All lessons in Beginner