0
0
Typescriptprogramming~15 mins

How TypeScript infers types automatically - Try It Yourself

Choose your learning style9 modes available
How TypeScript infers types automatically
📖 Scenario: Imagine you are creating a small program to store information about a book. You want to see how TypeScript can guess the types of your variables without you telling it explicitly.
🎯 Goal: You will create variables with values and see how TypeScript automatically understands their types. Then you will write code that uses these variables, relying on TypeScript's type inference.
📋 What You'll Learn
Create variables with initial values without specifying types
Create a helper variable to hold a count
Use a function that uses the inferred types
Print the results to the console
💡 Why This Matters
🌍 Real World
When writing code, TypeScript helps by guessing types so you write less code and avoid mistakes.
💼 Career
Understanding type inference is important for working efficiently with TypeScript in real projects, improving code quality and developer productivity.
Progress0 / 4 steps
1
Create variables with initial values
Create a variable called title and set it to the string "The Great Gatsby". Then create a variable called pages and set it to the number 180.
Typescript
Need a hint?

TypeScript will guess that title is a string and pages is a number because of the values you assign.

2
Add a helper variable
Create a variable called copiesSold and set it to the number 5000.
Typescript
Need a hint?

This variable will also have its type inferred as a number.

3
Use a function with inferred types
Create a function called getBookSummary that takes no parameters and returns a string combining title and pages in this format: "The Great Gatsby has 180 pages.". Use the variables title and pages inside the function.
Typescript
Need a hint?

TypeScript knows title is a string and pages is a number, so you can use them directly in the template string.

4
Print the result
Write a console.log statement to print the result of calling getBookSummary().
Typescript
Need a hint?

This will show the combined string in the console, demonstrating how TypeScript inferred the types correctly.