Inferred Typing and Duck Typing

Discover how TypeScript uses inferred typing for variables and employs duck typing for object compatibility.

We'll cover the following

Inferred typing is a feature of TypeScript that allows the type of a variable or expression to be determined based on the context in which it appears rather than being explicitly specified with a type annotation.

Duck typing checks the compatibility of an object with a particular type based on the presence of certain properties or methods rather than the object’s actual type.

We will explore these concepts in greater detail and see how they can be used in practice.

Inferred typing

TypeScript uses a technique called inferred typing, or type inference, to determine the type of a variable. This means that even if we do not explicitly specify the type of a variable, the compiler will determine its type based on when it was first assigned. Again, once the variable has a type, normal type comparisons will be used.

As an example of this, consider the following code:

Get hands-on with 1400+ tech skills courses.