🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
In this chapter, we will explore type inference in TypeScript. Type inference is a powerful feature that allows the TypeScript compiler to automatically determine the type of a variable based on its value. This helps in reducing the amount of explicit type annotations while still maintaining type safety.
Table of Contents
- Definition
- How Type Inference Works
- Type Inference with Variables
- Type Inference with Functions
- Contextual Typing
- Examples and Output
- Conclusion
Definition
Type inference in TypeScript refers to the compiler's ability to automatically determine the type of a variable, function return type, or function parameter based on the value assigned to it or the context in which it is used. This feature helps in writing cleaner and more concise code while maintaining type safety.
How Type Inference Works
TypeScript uses various strategies to infer types. When you declare a variable and initialize it with a value, TypeScript infers the type of the variable from the value. Similarly, when you return a value from a function, TypeScript infers the return type of the function.
Type Inference with Variables
Example
This example demonstrates how TypeScript infers the type of variables.
let age = 25; // TypeScript infers the type as number
let name = "Ravi"; // TypeScript infers the type as string
let isStudent = true; // TypeScript infers the type as boolean
console.log(`Age: ${age}, Name: ${name}, Is Student: ${isStudent}`);
Output
Age: 25, Name: Ravi, Is Student: true
Type Inference with Functions
Example
This example demonstrates how TypeScript infers the return type of a function.
function add(a: number, b: number) {
return a + b; // TypeScript infers the return type as number
}
let result = add(5, 10);
console.log(result);
Output
15
Contextual Typing
Contextual typing is a form of type inference where the type of an expression is determined by its context. This often happens in situations like event handlers, where TypeScript infers the type of parameters based on their usage.
Example
This example demonstrates contextual typing with an event handler.
document.addEventListener("click", (event) => {
console.log(event.clientX, event.clientY); // TypeScript infers the type of event as MouseEvent
});
Explanation
In the above example, TypeScript infers the type of the event parameter as MouseEvent based on the context of the addEventListener function.
Examples and Output
Example 1: Type Inference with Variables
This example shows how TypeScript infers the types of different variables.
TypeScript Code (src/index.ts)
let age = 25; // TypeScript infers the type as number
let name = "Ravi"; // TypeScript infers the type as string
let isStudent = true; // TypeScript infers the type as boolean
console.log(`Age: ${age}, Name: ${name}, Is Student: ${isStudent}`);
Example 2: Type Inference with Functions
This example shows how TypeScript infers the return type of a function.
TypeScript Code (src/index.ts)
function add(a: number, b: number) {
return a + b; // TypeScript infers the return type as number
}
let result = add(5, 10);
console.log(result);
Example 3: Contextual Typing
This example shows how TypeScript uses contextual typing to infer the type of parameters in an event handler.
TypeScript Code (src/index.ts)
document.addEventListener("click", (event) => {
console.log(event.clientX, event.clientY); // TypeScript infers the type of event as MouseEvent
});
Compiling to JavaScript
To compile the TypeScript code to JavaScript, run the TypeScript compiler:
tsc src/index.ts
Output in JavaScript (src/index.js)
// Type Inference with Variables
var age = 25; // TypeScript infers the type as number
var name = "Ravi"; // TypeScript infers the type as string
var isStudent = true; // TypeScript infers the type as boolean
console.log("Age: " + age + ", Name: " + name + ", Is Student: " + isStudent);
// Type Inference with Functions
function add(a, b) {
return a + b; // TypeScript infers the return type as number
}
var result = add(5, 10);
console.log(result);
// Contextual Typing
document.addEventListener("click", function (event) {
console.log(event.clientX, event.clientY); // TypeScript infers the type of event as MouseEvent
});
Running the JavaScript
To see the output of the compiled JavaScript code, run the JavaScript file using Node.js:
node src/index.js
Conclusion
In this chapter, we covered type inference in TypeScript, including how TypeScript infers types for variables, function return types, and function parameters.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment