CodeBlanks Logo Icon CodeBlanks

Inference with const

Learn literal type inference with const.

Inference with const

With const, TypeScript infers a literal type, meaning the exact value becomes the type. In const x = 5, the type of x is not number but the literal type 5. This is because const variables cannot be reassigned.

const x = 5;          // type: 5
const y = "merhaba";   // type: "merhaba"

const uses a literal type because the value never changes.

let vs const inference difference

With let, TypeScript widens the type: let x = 5 gives type number. With const, the literal type is preserved: const x = 5 gives type 5. This difference arises because let variables can receive other values of the same type, while const never changes.

let a = 5;      // type: number
const b = 5;    // type: 5

let gives a wide type; const gives a narrow literal type.

Practice Multiplication with const and let

Define a const named carpan with value 3. Define a let named deger with value 7. Print the result of carpan * deger with console.log.

Starter code

index.ts
// carpan adında bir const tanımla, değeri 3
// deger adında bir let tanımla, değeri 7
// carpan * deger sonucunu yazdır

Sample solution

index.ts
const carpan = 3;
let deger = 7;
console.log(carpan * deger);

Expected output

21

Questions and answers

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

1 In <code>const renk = "kırmızı";</code>, what is the inferred type of <code>renk</code>?

  • string (general type)
  • const (keyword)
  • "kırmızı" (literal type) Correct answer
  • renk (variable name)

Explanation: Since <code>const</code> does not change, TypeScript infers the exact value as a literal type; the type of <code>renk</code> is <code>"kırmızı"</code>, not the general <code>string</code>.

2 Find the const literal type

Question
const kod = 200;
// kod'un türü: ____
Answer
const kod = 200;
// kod'un türü: 200

Explanation: When declared with <code>const</code>, TypeScript makes the exact value the literal type; since <code>kod</code>'s value is <code>200</code>, its type is <code>200</code>, not the general <code>number</code>.

3 const inference concepts

Term Meaning
const x = "a" Literal type inference
let x = "a" General type inference
const x = 5 Type: 5 (literal)
const inference Produces exact value type

All lessons in Beginner