TypeScript - Implicit Typing


TypeScript is a statically typed programming language that is a superset of JavaScript. It is used for large-scale web applications that require strict typing, object-oriented programming concepts, and code reusability. One of the most important features of TypeScript is the ability to infer types automatically. This feature is known as implicit typing.

Implicit typing is a feature that allows TypeScript to automatically determine the type of a variable at the time of its initialisation. This makes coding faster, easier, and less error-prone. This article will explore the concept of implicit typing in TypeScript and discuss its benefits with examples.

What is Implicit Typing?

Implicit typing is a TypeScript feature that automatically infers the type of a variable based on its initial value or usage in the code, rather than requiring the programmer to explicitly declare the type.

This means that developers don't need to explicitly specify the type of a variable, as TypeScript infers it based on the assigned value. TypeScript uses type inference to provide type information when there is no explicit type annotation, which occurs in various places in the code. For example,

let myVar = 10; // TypeScript infers the type of myVar as number
let myString = "Hello, World!"; // string is type of myString

In the above example, TypeScript automatically infers the type of myVar as number and myString as string based on the values assigned to them.

In TypeScript, type inference takes place during variable and member initialization, when assigning default values to function parameters, and when determining the return type of functions. This process is typically simple and automatic, allowing the language to infer types based on context and usage within the code.

Examples of Implicit Typing

Let's look at some examples to understand how implicit typing works in TypeScript.

Example 1: Inferring the Type of a Variable

In the above example, TypeScript infers the type of myVar as number, myString as string, and myBoolean as boolean based on the values assigned to them.

let myVar = 10; // TypeScript infers the type of myVar as number
let myString = "Hello, World!"; // infers the type of myString as string
let myBoolean = true; // infers the type of myBoolean as Boolean
console.log(`The type of myVar is: ${typeof myVar}`);
console.log(`The type of myString is: ${typeof myString}`);
console.log(`The type of myBoolean is: ${typeof myBoolean}`);

Output

The type of myVar is: number
The type of myString is: string
The type of myBoolean is: boolean

Example 2: Inferring the Type of a Function

In the above example, TypeScript can infer the type of the add function parameters as number using the default values assigned to them even if they are not explicitly defined. Using the inferred types of the parameters it can also determine the return type of the function.

function add(a = 2, b = 5) {
   console.log(`The typeof a is: ${typeof a}`);
   console.log(`The typeof b is: ${typeof b}`);
   return a + b;
}
add(4, 5);

Output

The typeof a is: number
The typeof b is: number

Example 3: Inferring the Type of an Array

In the below code, isNumberArray is a type guard function that checks if the input arr is an array and if every element in the array is of type "number". The is keyword is used to assert the type within the function signature.

Then, we declare myArray as any type to bypass type checking temporarily. We can then use the type guard isNumberArray to check if myArray is a valid number[] array. If the type guard returns true, it means the type assertion is correct, and we can safely treat myArray as an array of numbers.

function isNumberArray(arr: any): arr is number[] {
   return Array.isArray(arr) && arr.every((value) => typeof value === "number");
}

const myArray = [1, 2, 3];
if (isNumberArray(myArray)) {
   // Here, myArray is recognized as number[]
   console.log("myArray is an array of numbers");
} else {
   console.log("myArray is not an array of numbers");
}

On compiling, it will generate the following JavaScript code −

function isNumberArray(arr) {
   return Array.isArray(arr) && arr.every(function (value) { return typeof value === "number"; });
}
var myArray = [1, 2, 3];
if (isNumberArray(myArray)) {
   // Here, myArray is recognized as number[]
   console.log("myArray is an array of numbers");
}
else {
   console.log("myArray is not an array of numbers");
}

Output

myArray is an array of numbers

How Implicit Types are Determined?

Inferring the types during initialization, getting the types of function parameters using their provided default values or determining the return types of functions are pretty straightforward.

When TypeScript infers a type from multiple expressions, it uses the expression types to determine the "best common type".

let x = [4, "hello", null]

The inferred type of the x variable is the best common types for each value in the array. Hence, the inferred type becomes (number|string|null)[].

Since the “best common type” has to be chosen from the provided candidate types, there are some cases where types share a common structure, but no one type is the super type of all candidate types. For example −

let bouquet = [new Tulip(), new Dahlia(), new Orchid()];

The inferred type by TypeScript in this case is (Tulip|Dahlia|Orchid)[] but ideally we may want bouquet to be inferred as an Flower[].

However, there is no object that is strictly of type Flower[] in the array, we make no inference about the array element type. Hence we need to explicitly provide the type when no one type is a super-type of all other candidate expressions −

Let bouquet: Flower[] = [new Tulip(), new Dahlia(), new Orchid()];

When no best common type is found, the resulting inference is the union array type, (Tulip|Dahlia|Orchid)[].

Benefits of Implicit Typing

The benefits of implicit typing in TypeScript are −

  • Faster coding − Implicit typing saves time and effort by eliminating the need to explicitly specify the type of every variable.

  • Fewer errors − Since TypeScript automatically infers the type of a variable, there is less chance of making mistakes while declaring the type of a variable.

  • Code readability − Implicit typing makes the code more readable as it reduces the amount of code that needs to be written.

Conclusion

Implicit typing is a powerful feature of TypeScript that allows the language to automatically infer the types of variables, functions, arrays, and objects based on the values assigned to them. This feature helps developers write cleaner and more concise code, while also reducing the likelihood of errors. In addition, it saves time and effort as developers do not need to explicitly specify the types of every variable in their code. Overall, implicit typing is a valuable feature that contributes to the popularity of TypeScript among developers.

Updated on: 22-Aug-2023

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements