CodeBlanks Logo Icon CodeBlanks

Summary - Type annotation

Write a calculation function with explicit types.

Summary - Type annotation

Type annotations make your code explicit: variables get : type, parameters get : type, and the return type goes after the parameter list. Together they form a fully typed signature.

function alan(genislik: number, yukseklik: number): number {
  return genislik * yukseklik;
}

Explicit types make code easier to read and maintain.

Practice Fully typed calculation function

Define a function named dikdortgenAlani with genislik and yukseklik parameters of type number and return type number. The function should return genislik * yukseklik. Print the result of calling dikdortgenAlani(5, 3) with console.log.

Starter code

index.ts
// dikdortgenAlani adında bir fonksiyon tanımla
// genislik ve yukseklik parametreleri number olsun
// dönüş türü number olsun
// genislik * yukseklik değerini döndür
// dikdortgenAlani(5, 3) sonucunu yazdır

Sample solution

index.ts
function dikdortgenAlani(genislik: number, yukseklik: number): number {
    return genislik * yukseklik;
}
console.log(dikdortgenAlani(5, 3));

Expected output

15

Questions and answers

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

1 Which is a function with full type annotations?

  • function hesapla(a: number, b) { return a + b; }
  • function hesapla(a, b): number { return a + b; }
  • function hesapla(a: number, b: number): number { return a + b; } Correct answer
  • function hesapla(a, b) { return a + b; }

Explanation: In a full type annotation, both parameters and the return type must be written explicitly; <code>a: number, b: number): number</code> does this.

2 Add the return type

Question
function dikdortgenAlani(genislik: number, yukseklik: number)____ { return genislik * yukseklik; }
Answer
function dikdortgenAlani(genislik: number, yukseklik: number): number { return genislik * yukseklik; }

Explanation: The function returns <code>genislik * yukseklik</code>, which is a number, so the return type must be <code>: number</code>. <code>: string</code>, <code>: void</code> and <code>: boolean</code> are wrong types.

3 Annotation summary

Term Meaning
let x: number Variable annotation
function f(a: number) Parameter annotation
function f(): number Return type annotation
: type Type declaration

All lessons in Beginner