![]() |
In TypeScript, the duck-typing feature ensures type safety. As a result of the duck-typing rule, the TypeScript compiler verifies that two objects are identical in terms of having matching properties and methods. This technique is used to compare two objects by determining if they have the same type-matching properties and object members. Example 1: In the below code we create three classes: pigeon, penguin, and owl. All three classes have a property called “sound“. Penguin class has an additional method called swim. When we assign owl to penguin variable it gives no error as they both have the same properties. The same goes when the pigeon is assigned to the owl type variable or when the penguin object is assigned to the pigeon type variable. But we cannot assign the pigeon-type objects to the penguin as the penguin has an additional class method but the pigeon doesn’t.
Output: When we compile the .ts file we get this error: error TS2741: Property ‘swim’ is missing in type ‘Pigeon’ but required in type ‘Penguin’. let penguin: Penguin = new Pigeon(); When we run the .js file using the command: node filename.js Output: A pigeon hoots
An owl coos
A pigeon peeps
A penguin coos Example 2: In this example, we create two classes ordinary_phone and iPhone. This example is just for the sake of having a better understanding. Both normal phones and iPhones help users call and text, in the example iPhone has a method camera_experience(). So iPhone consists of all the functions of an ordinary phone and it has a good camera. So, if we create a variable of type iPhone and pass ordinary_phone object it will work, but the opposite isn’t possible as ordinary_phone doesn’t consist of camera_experience() method.
Output: After compiling the .ts file we get this error: error TS2339: Property ‘camera_experience’ does not exist on type ‘ordinary_phone’. console.log(phone1.camera_experience()); ~~~~~~~~~~~~~~~~~ one.ts:427:5 – error TS2741: Property ‘camera_experience’ is missing in type ‘ordinary_phone’ but required in type ‘iphone’. let phone2: iphone = new ordinary_phone(); ~~~~~~ one.ts:419:3 camera_experience() { ~~~~~~~~~~~~~~~~~ ‘camera_experience’ is declared here. When we run the .js file using the command: node filename.js Output: [ 'calls', 'messages' ]
i am very well known for my camera
undefined FAQs – TypeScript Duck-TypingWhat is duck-typing in TypeScript?
How does the TypeScript compiler use duck-typing to ensure type safety?
Can you assign objects of different classes with the same properties to each other in TypeScript?
What happens if an object is missing a method or property required by another type?
Can duck-typing be used with interfaces in TypeScript?
|
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |