Inferred And Duck Typing In TypeScript

Inferred Typing

TypeScript also uses a technique called inferred typing, in case you do not explicitly specify the type of your variable. In other words, if we don't specify the data type for a variable then TypeScript compiler finds what type of data is assigning the first type and sets the data type of this variable. If further we try to assign the value of another datatype, then we will get an error.



In the example given above, we don't set the data type for complexType variable but the first time we assign a "string" type data into the variable, so TypeScript compiler sets the type of complexType to the string . Now, if we try to assign the another datatype value into the variable, then we will get the error.

Duck Typing

Duck type is similar to inferred type, but it is used for complex type. According to TypeScript for complex type data type, we can't change the signature of a variable. For example, if we assign an object that has two properties like Id, name and next time we assign an object that contains more properties or fewer properties or both properties are not (Id, name) then TypeScript throws an error. This is known as Duck typing.