Menu
Coddy logo textTech

Type Inference in Action

Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 10 of 73.

When you initialize a variable with a value, TypeScript examines that value and automatically assigns the appropriate type:

let message = "Hello, World!";  // TypeScript infers: string
let count = 42;                 // TypeScript infers: number
let isActive = true;            // TypeScript infers: boolean

This type inference provides the same type safety as explicit annotations, but with cleaner, more readable code. TypeScript will still catch type errors if you try to reassign these variables to incompatible values.

Type inference works because TypeScript analyzes the initial value at the moment of assignment. A string value tells TypeScript the variable should be of type string, a numeric value indicates number, and so on.

challenge icon

Challenge

Easy

Create three variables using TypeScript's type inference without explicit type annotations:

Declare a variable named companyName and initialize it with the string "TechCorp".

Declare a variable named employeeCount and initialize it with the number 150.

Declare a variable named isPublic and initialize it with the boolean value false.

Print all three variables to the console on separate lines in the order they were declared.

TypeScript will automatically infer the correct types based on the initial values you assign to each variable.

Try it yourself

// TODO: Write your code here
// Declare the three variables with their initial values
// Remember to use TypeScript's type inference (no explicit type annotations needed)

// Print all three variables to the console
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To TypeScript