Open In App

TypeScript Duck-Typing

Last Updated : 23 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

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. 

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

FAQs – TypeScript Duck-Typing

What is duck-typing in TypeScript?

Duck-typing is a feature in TypeScript that ensures type safety by comparing objects based on their shape (properties and methods) rather than their explicit types. If two objects have the same set of properties and methods, they are considered to be of the same type.

How does the TypeScript compiler use duck-typing to ensure type safety?

The TypeScript compiler checks whether two objects have the same type by comparing their properties and methods. If an object is missing a property or method required by another type, the compiler will raise a compile-time error.

Can you assign objects of different classes with the same properties to each other in TypeScript?

Yes, you can assign objects of different classes to each other if they have the same properties and methods. This is because TypeScript uses structural typing, which relies on the shape of the objects rather than their explicit class names.

What happens if an object is missing a method or property required by another type?

If an object is missing a method or property required by another type, the TypeScript compiler will raise a compile-time error, indicating that the assignment is not valid.

Can duck-typing be used with interfaces in TypeScript?

Yes, duck-typing can be used with interfaces in TypeScript. When you define an interface, you are defining the shape of an object. Any object that has the same properties and methods as the interface can be assigned to a variable of that interface type.



Similar Reads

three90RightbarBannerImg