Why TypeScript?
- TypeScript course
- Beginner
- Lesson 2/89
- 4 min
Learn how type safety catches errors early.
Why TypeScript?
TypeScript catches type errors at compile time, not at runtime. So if a function expects a number and you pass a string, the compiler warns you.
function topla(a: number, b: number): number {
return a + b;
}
topla(5, "10"); // Compile errorThis way you spot errors during writing, not in production.
Type safety
Type safety ensures that variables and parameters are used only with their expected types. TypeScript flags wrong usage, preventing unexpected crashes.
let bitti: boolean = false;
bitti = "evet"; // Error: string is not assignable to booleanThis makes the code's behavior more predictable.
Practice Type-safe function
Write a function named kareAl. Its parameter is x: number, its return type is number. Its body returns x * x. Then print the result of kareAl(6) with console.log.
Starter code
// kareAl fonksiyonunu tanımla
// parametre: x: number, dönüş: number
// kareAl(6) sonucunu yazdırSample solution
function kareAl(x: number): number {
return x * x;
}
console.log(kareAl(6));Expected output
36
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When does TypeScript catch type errors?
- Only in the browser
- At compile time Correct answer
- Only in production
- At runtime
Explanation: The TypeScript compiler checks types during compilation. This lets you see errors before running the code.
2 Pick the right type
let acik: ____ = true;
let acik: boolean = true;
Explanation: The value "true" is of type boolean. Assigning string or number gives a compile error.
3 Error catching times
| Term | Meaning |
|---|---|
Derleme zamanı |
Errors caught while writing |
Tür açıklaması |
Specifies the expected type |
Çalışma zamanı |
When JS catches errors |
Tür güvenliği |
Prevents wrong usage |