This page looks best with JavaScript enabled

Type Inference In TypeScript

 ·  β˜• 4 min read  ·  ✍️ Adesh

What Is Type System?

A type system is a set of rules that assigns a property calledΒ typeΒ to the various constructs of aΒ computer program, such asΒ variables,Β expressions,Β functionsΒ orΒ modules. Types play a very important role in programming. Type system provides a safety mechanism that helps us to avoid any programming error related to types.

The Type System checks the validity of the supplied values before they are stored or manipulated by the program. This ensures that the code behaves as expected.

Typing

In the context of the type systems β€” static means at compile-time, whereas dynamic means at runtime.

Static Typing vs Dynamic Typing

In a statically typed language, the compiler knows the types of variables, parameters and members of objects at compile time. The compiler can use that information to perform type checks and to optimize the compiled code.

Whereas in dynamically typed language β€” like JavaScript β€” types of variables are not known at compile time.

TypeScript β€” Static Typing

Then the Microsoft developed TypeScript β€” an open-source programming language from the shortcomings of JavaScript for the development of large-scale applications.

TypeScript β€” is a strict superset of JavaScript, and it adds optional static typing to the language. TypeScript is a strongly-typed superset of JavaScript, which means it adds some syntactical benefits to the language while still letting you write normal JavaScript if you want to.

Implicit & Explicit Typing

There are two ways of declaring types in TypeScript β€” Implicit & Explicit.

Implicit Typing β€” No type is written with the variable name, and let the Typescript determine the type of the variable by its assigned value. The code is concise but leaves space for doubt.

1
2
const num1 = 5 // Implicit as number
const str = 'test' // Implicit as string

Explicit Typing β€” type is plainly written down. The code is more verbose but leaves less place for doubts.

1
2
const num1: number = 5
const str: string = 'test'

Type Inference Basics

In TypeScript, there is no such hard rule to use explicit typing or annotate the type. Type Inference is a very powerful feature of TypeScript. The basic idea is, we keep the type safety of our codebase, but we declare types less. Less investment cost, same profit.

In TypeScript, the compiler can infer the type information if no explicit type has been specified. The inference is done based on the assigned value. TypeScript compiler is smart enough to determine the type based on its value. That sounds cool!

Type Inference Scenario

There are different scenario β€” when TypeScript applies type inferences.

TypeScript infers the Types in the following scenario, when:

  • Variables are initialized.

  • Default values are set for parameters.

  • Function return types are determined.

Variable Type Inference

1
let counter = 10;

In the above code, we haven’t explicitly annotated any type with counter and initialized the variable with number 10. Now, TypeScript compiler infers its type based on the assigned value to it. The value of the counter is number, hence type of counter will be inferred as a number.

Now, TypeScript compiler will throw an error, if you try to perform any operation β€” which is not compatible with number type.

variable infer in typescript

We tried to use the length() of the variable counter, and TypeScript immediately warned us about the error.

Default Parameter Type Inference

Default parameters are also type inferred by TypeScript compiler. See below code.

default parameter type infer

Here, we passed the default parameter and assigned its value to number 10. TS Compiler infers its type to number. Again, when we try to use length() property, it will warn us with a red underline.

default parameter type inference

Function Return Type

The return type of a function is also inferred by the returning value. Let’s take a look at this tiny function.

function type infer

In the above code, the return type of add() function is number. So, the result of the function will be returned to number type, not the string type.

Summary

Type Inference is one of the most fundamental concepts, and you should master it if you want to use TypeScript effectively. Though Type Inference reduces the cost of typing with the type safety remain the same, we should keep a good balance between what we type explicitly and implicitly.

Further Reading

How Change Detection Works In Angular

Getting Started With Docker

Docker Introduction With Its Architecture And Components

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect