CodeBlanks Logo Icon CodeBlanks

Summary - Type inference

Write a variable tracker by combining inference rules.

Summary - Type inference

TypeScript inference rules: let gives a wide type, const gives a literal type, and arrays find the best common type (or union type). Together these rules provide strong type safety with minimal type annotations.

let adet = 0;            // number
const birim = "adet";    // "adet"
let liste = [1, 2, 3];   // number[]

Inference keeps code short while preserving safety.

Practice Variable tracker program

Define a let named adet with value 0. Define a const named birim with value "adet". Define an array named liste with value [1, 2, 3]. Print adet, birim, and the first element of liste in order with console.log.

Starter code

index.ts
// adet adında bir let tanımla, değeri 0
// birim adında bir const tanımla, değeri "adet"
// liste adında bir dizi tanımla, üç sayı içersin
// adet, birim ve liste'nin ilk öğesini sırayla yazdır

Sample solution

index.ts
let adet = 0;
const birim = "adet";
let liste = [1, 2, 3];
console.log(adet);
console.log(birim);
console.log(liste[0]);

Expected output

0
adet
1

Questions and answers

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

1 In <code>const x = 100;</code>, what is the inferred type of <code>x</code>?

  • any
  • 100 (literal type) Correct answer
  • number
  • const

Explanation: Since <code>const</code> does not change, TypeScript makes the exact value the literal type; the type of <code>x</code> is <code>100</code>, not the general <code>number</code>.

2 Find the missing part of the union type

Question
let karisik = [1, "iki", true];
// çıkarılan tür: (number | string | ____)[]
Answer
let karisik = [1, "iki", true];
// çıkarılan tür: (number | string | boolean)[]

Explanation: The array contains a number, a string, and a boolean, so the union type is <code>(number | string | boolean)[]</code>; the third type is <code>boolean</code>.

3 Inference summary

Term Meaning
let x = 5 Wide type (number)
const x = 5 Narrow literal type (5)
[1, "a"] Union type array
Type inference Deriving type from value

All lessons in Beginner