TypeScript type checking example
TypeScript Basic: Exercise-4 with Solution
Write a TypeScript program that declares a variable as a number and then tries to assign a string to it to see type checking in action.
Sample Solution:
TypeScript Code:
// Declare a variable as a number
let n: number = 42;
// Attempt to assign a string to the number variable (Type Error)
n = "Hello, TypeScript!"; // This line will result in a type error
// Attempt to print the value (won't reach this line due to the error above)
console.log("n = ", n);
Explanations:
In the exercise above -
- First, declare a variable 'n' and explicitly specify its type as 'number' by using the 'number' type annotation.
- We then attempt to assign a string value "Hello, TypeScript!" to the 'n' variable. This is a type mismatch because we're trying to assign a string to a variable declared as a number.
- TypeScript's type checking will catch this error and prevent the program from running successfully.
- Therefore, the console.log statement won't be reached due to the type error.
Output:
Error: Type 'string' is not assignable to type 'number'.
TypeScript Editor:
See the Pen TypeScript by w3resource (@w3resource) on CodePen.
Previous: TypeScript variable types and basic operations.
Next: TypeScript type inference example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/typescript-exercises/typescript-basic-exercise-4.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics