Javatpoint Logo
Javatpoint Logo

TypeScript Duck-Typing

According to TypeScript, Duck-Typing is a method/rule used to check the type compatibility for more complex variable types.

TypeScript uses the duck-typing method to compare one object with other objects by checking that both objects have the same type matching names or not. It means we cannot change the signature of a variable. For example, if we assign an object that has two properties like name, address and next time we assign an object which contains more properties or fewer properties or both properties are not (name, address), then the TypeScript compiler will generate the compile-time error. The concept is known as Duck typing.

The duck-typing feature provides type safety in TypeScript code.

Through the duck-typing rule TypeScript compiler checks that an object is same as other object or not.

According to the duck-typing method, both objects must have the same properties/variables types.


TypeScript Duck-Typing

In the above example, we can see that it does not allow substitution of a Lion for a Goat because the Goat class has an additional method (so Lion fails duck typing). Dog and Lion are substitutable in duck typing because there's nothing a lion can do that a dog cannot, and vice versa.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA