The goal of this tutorial is to help you understand the concept of Type Inference in TypeScript and its practical applications.
By the end of this tutorial, you will be able to:
You should have a basic understanding of TypeScript and its static types.
TypeScript is a statically typed language, which means we need to specify the type of values that a symbol can hold. But sometimes, TypeScript can predict the type of a value on its own, and this is called Type Inference.
When you assign a value to a variable without specifying its type, TypeScript will infer the type based on the assigned value.
let message = "Hello, TypeScript!";
Here, TypeScript infers the type of message as string.
let number = 10; // TypeScript infers the type as number
let isTrue = true; // TypeScript infers the type as boolean
// TypeScript infers the return type as number
function getDouble(num) {
return num * 2;
}
// TypeScript infers the type as { name: string, age: number }
let user = {
name: "John",
age: 30
};
In this tutorial, we have covered:
Declare a variable message and assign a string value to it. What is the inferred type of message?
Write a function add that takes two numbers and returns their sum. What is the inferred return type of add?
Declare a variable user and assign an object with properties name and age to it. What is the inferred type of user?
message is string.add is number.user is { name: string, age: number }.Keep practicing with more complex types and functions to fully grasp the concept of Type Inference. Happy coding!