Basic inference
- TypeScript course
- Beginner
- Lesson 34/89
- 4 min
Learn how type inference works.
Basic inference
TypeScript automatically infers a variable's type from the value you assign. This is called type inference. You do not have to write explicit types on every variable; TypeScript determines the type from the assigned value.
let yas = 25; // infers number
let isim = "Ali"; // infers string
let aktif = true; // infers booleanInference provides type safety with less code.
Inference and type mismatch
The inferred type depends on the type of the assigned value. A string gives string, a number gives number, a boolean gives boolean. The inferred type prevents assigning a different type later.
let x = 5;
x = "metin"; // error: expected numberInference is based on the first assignment and does not change afterwards.
Practice Declare variables with inference
Declare three variables without type annotations: assign "merhaba" to mesaj, 10 to adet, and true to aktif. Print all three values in order with console.log.
Starter code
// mesaj değişkenine bir dize ata (tür yazma)
// adet değişkenine bir sayı ata (tür yazma)
// aktif değişkenine true ata (tür yazma)
// mesaj, adet, aktif sırayla yazdırSample solution
let mesaj = "merhaba";
let adet = 10;
let aktif = true;
console.log(mesaj);
console.log(adet);
console.log(aktif);Expected output
merhaba 10 true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>let isim = "Ali";</code>, what is the inferred type of <code>isim</code>?
- any
- string Correct answer
- number
- "Ali" (literal)
Explanation: When a string is assigned with <code>let</code>, TypeScript infers the wide <code>string</code> type; the literal type <code>"Ali"</code> is only inferred with <code>const</code>.
2 Write the type matching the inference
let x = "merhaba";
let y: ____ = x;
let x = "merhaba";
let y: string = x;
Explanation: Since <code>x</code> is assigned a string, its inferred type is <code>string</code>; <code>y</code> receives <code>x</code>, so it must also be <code>string</code>.
3 Inference concepts
| Term | Meaning |
|---|---|
let x = 5 |
Infers number |
let x = "a" |
Infers string |
let x = true |
Infers boolean |
Type inference |
Automatic type determination |