Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptTypeScript Duck-Typing

TypeScript Duck-Typing

In TypeScript programming, the duck-typing feature ensures type safety. As a result of the duck-typing rule, the TypeScript compiler verifies that two objects are identical. 

The duck-typing technique in TypeScript is used to compare two objects by determining if they have the same type matching properties and objects members or not. For example, if we assign an object with two properties and a method and the second object is only assigned with two properties. The typescript compiler raises a compile-time error in such situations when we create a variable of object1 and assign it a variable of the second object type. Let’s understand luck typing with an example.

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.

Javascript




class Pigeon {
  sound = "coos";
}
  
class Owl {
  sound = "hoots";
}
  
class Penguin {
  sound = "peeps";
  swim() {
    console.log("I'm a bird and i can swim");
  }
}
  
let pigeon: Pigeon = new Owl();      // Works
let owl: Owl = new Pigeon();         // Works
let pigeon2: Pigeon = new Penguin(); // Works
let penguin: Penguin = new Pigeon(); // Compile time error
  
// Printing values
console.log("A pigeon " + pigeon.sound);
console.log("An owl " + owl.sound);
console.log("A pigeon " + pigeon2.sound);
console.log("A penguin " + penguin.sound);


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. 

Javascript




class ordinary_phone {
  functions = ["calls", "messages"];
}
  
class iphone {
  functions = ["calls", "messages"];
  camera_experience() {
    console.log("i am very well known for my camera");
  }
}
  
let phone1: ordinary_phone = new iphone();
  
console.log(phone1.functions);
console.log(phone1.camera_experience());
  
let phone2: iphone = new ordinary_phone();


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

Reference: https://www.typescriptlang.org/docs/handbook/interfaces.html

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments