w3resource

TypeScript type inference example

TypeScript Basic: Exercise-5 with Solution

Write a TypeScript program that declares a variable without specifying its type and shows how TypeScript infers the type based on the assigned value.

Sample Solution:

TypeScript Code:

// Declare a variable without specifying its type
let temp = 100; // TypeScript will infer the type based on the assigned value

// Check the inferred type
console.log("Type of temp:", typeof temp);

// Attempt to reassign the variable with a different type
temp = "Hello, TypeScript!"; // TypeScript will catch this as a type error

// Display the value (won't reach this line due to the error above)
console.log("My Variable:", temp);

Explanations:

In the exercise above -

  • First, declare a variable 'temp' without specifying its type explicitly. TypeScript will infer the type based on the assigned value, 100.
  • We use typeof to check the inferred type of 'temp' and log it to the console.
  • We then attempt to reassign 'temp' with a string "Hello, TypeScript!". TypeScript's type inference will initially set 'temp' as type number, and it will catch a type error when we try to assign a string to it.
  • Therefore, the console.log statement for displaying the value 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 type checking example.
Next: TypeScript type conversion example.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-5.php