w3resource

TypeScript Program - Declare, assign and print variables

TypeScript Basic: Exercise-1 with Solution

Write a TypeScript program that declares a variable `name` and assigns it a string value. Also declare a variable `age` and assign it a number value. Finally print the values of name and age.

Sample Solution:

TypeScript Code:

// Declare variables
let emp_name: string = "Ippolit Aren";
let age: number = 25;

// Print values
console.log("Name:", emp_name);
console.log("Age:", age);

Explanations:

In the exercise above -

  • Use the 'let' keyword to declare the variables 'emp_name' and 'age'.
  • Specify the types of these variables explicitly using type annotations. 'emp_name' is of type 'string', and 'age' is of type 'number'.
  • Assign values to 'emp_name' and 'age'.
  • Finally, use console.log() to print the values of 'emp_name' and 'age' to the console.

Output:

"Name:"
"Ippolit Aren"
"Age:"
25

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript Basic Exercises Home
Next: TypeScript variable declaration and scoping: let, const, and var.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.