Open In App

TypeScript Inference

TypeScript Inference defines that TypeScript will automatically detect variables data type, functions return type, Object types, Array Types, etc. This detection is based on the values assigned to the variables and the usage of the code or function calls.

What is Inference?

Example 1: Inference of Number and String Types: TypeScript will infer types by looking at the initial values of the variables and functions return values and it will determine the appropriate types for the variables and function return types by checking their usage throughout the code.






let x = 10;
  
// TypeScript infers x to be of type number.
let message = "Hello , GeeksForGeeks";
  
//TypeScript infers message to be of type string.
console.log(`Value of x is ${x}`);
console.log(`Message : ${message}`);

Output:

Value of x is 10
Message : Hello , GeeksForGeeks

Example 2: TypeScript can infer the types of arrays and objects based on their initial values.






// TypeScript infers array Games of type string.
let Games = 
    ["Golf", "Cricket", "Hockey", "Chess"];
  
// TypeScript infers array Games of type number.
let RollNos = [12, 14, 56, 7, 45];
for (let games of Games) {
    console.log(`Value of x is ${games}`);
}
for (let rollno of RollNos) {
    console.log(`Message : ${rollno}`);
}

Output :

Value of x is Golf
Value of x is Cricket
Value of x is Hockey
Value of x is Chess
Message : 12
Message : 14
Message : 56
Message : 7
Message : 45

Example 3: TypeScript can infer return types also with conditions of the functions based on the values returned from the functions and usage of the functions in the entire code.




function getMessage(isMorning: boolean, isEvening: boolean){
    if (isMorning) {
        return "Good morning!";
    } else if(isEvening){
        return "Good evening!";
    }
    else {
        return "Good night!";
    }
}
console.log(getMessage(false, true));

Output:

Output of the code.

Conclusion: TypeScript’s type inference is a feature that helps developers write simple and clean code by automatically detecting the type of variables and functions return types etc. It also enables writing strongly types code and in figuring out type related errors in initial development phase of the application.


Article Tags :