Variable annotation
- TypeScript course
- Beginner
- Lesson 30/89
- 4 min
Learn to give explicit types to variables.
Variable annotation
In TypeScript you give a variable an explicit type by writing : type after its name. This is an explicit type annotation. Without it, TypeScript infers the type from the assigned value.
let yas: number = 25; // explicit
let isim = "Ali"; // inferred: stringExplicit types improve code readability and safety.
When is an explicit type needed?
Since TypeScript can infer types automatically, an explicit type is not needed on every variable. However, when declaring a variable without an initial value, an explicit type is required. It can also be preferred for code clarity.
let x: number; // type required
x = 10;Without an initial value TypeScript cannot know the type, so you must provide an explicit type.
Practice Declare variables with explicit types
Declare a variable named yas of type number with value 25. Declare a variable named isim of type string with value "Ali". Print yas first, then isim, both with console.log.
Starter code
// yas adında bir number değişkeni tanımla, değeri 25
// isim adında bir string değişkeni tanımla, değeri "Ali"
// önce yas değerini yazdır
// sonra isim değerini yazdırSample solution
let yas: number = 25;
let isim: string = "Ali";
console.log(yas);
console.log(isim);Expected output
25 Ali
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>let x: string = "merhaba";</code> do?
- Converts x to string at runtime
- Prevents reassignment of x
- Explicitly declares x as string type Correct answer
- Makes x a constant
Explanation: Adding <code>: string</code> explicitly declares the variable's type; it does not change runtime behavior, only strengthens compile-time checking.
2 Add the variable type
let sayi: ____ = 42;
let sayi: number = 42;
Explanation: The variable is assigned <code>42</code>, so the correct type is <code>number</code>. <code>string</code> and <code>boolean</code> do not accept a number, and <code>void</code> is not used as a variable type.
3 Variable annotation concepts
| Term | Meaning |
|---|---|
let x: string |
Explicit type declaration |
let x = "a" |
Type inference |
let x: number = 5 |
Explicit type and value |
Değişken annotation |
Giving a type to a variable |