Type assertion vs casting
- TypeScript course
- Intermediate
- Lesson 68/89
- 4 min
Learn the difference between assertion and real casting.
Assertion vs conversion
Type assertion is compile-time only; it does not change the value at runtime. For example, "5" as number does not convert the value to the number 5; at runtime it is still the string "5". For real conversion, functions like Number() and String() are used.
const s: any = "5";
console.log((s as number) + 1); // "51"
console.log(Number(s) + 1); // 6Real conversion functions
For real type conversion at runtime, functions like Number(), String(), and Boolean() are used. These change the runtime type of the value. Assertion only affects TypeScript's type view.
const n = Number("42"); // number 42
const t = String(42); // string "42"Practice Assertion vs conversion difference
The s variable is of type any with value "5". First assert it as number with as number and assign to iddia; then do real conversion with Number() and assign to gercek. Add 1 to each and print on separate lines with console.log.
Starter code
// s degiskenini iddia yontemiyle number olarak isaretle
// Number fonksiyonuyla gercek donusum yap
// her degiskene 1 ekle ve ayri satirlarda yazdir
const s: any = "5";Sample solution
const s: any = "5";
const iddia = s as number;
const gercek = Number(s);
console.log(iddia + 1);
console.log(gercek + 1);Expected output
51 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is used to truly convert a string to a number?
- Assertion with <number>
- The typeof operator
- Assertion with as number
- The Number() function Correct answer
Explanation: as number and <number> are compile-time only; for real conversion Number() must be called.
2 Real numeric conversion
const s: any = "42";
// gercek donusum icin
const n = ____;
console.log(n + 1);
const s: any = "42";
// gercek donusum icin
const n = Number(s);
console.log(n + 1);
Explanation: For runtime conversion call Number(); as is compile-time only.
3 Assertion and conversion
| Term | Meaning |
|---|---|
as number |
Compile-time only |
Number(s) |
Runtime conversion |
String(n) |
Conversion to string |
Boolean(x) |
Boolean conversion |