Home >Web Front-end >JS Tutorial >Duck types in TypeScript

Duck types in TypeScript

WBOY
WBOYforward
2023-09-11 23:25:06874browse

TypeScript 中的 Duck 类型

What is duck typing?

First of all, we need to know what duck typing is. According to programmers, a situation in which an object's type is determined by its behavior (such as methods and properties) rather than its class is called "duck typing."

Duck typing in TypeScript

The use of interfaces in TypeScript makes duck typing possible. Interface means a set of methods and characteristics that describe the type that an object must belong to.

For example, if an interface defines functions, any object with a method named "myFunc()" can be considered to be of a specific type, regardless of its class. Greater code flexibility is achieved when two objects share the same behavior and can be used interchangeably.

Duck typing emphasizes evaluating an object's suitability for a task by considering its methods and properties rather than its actual type. An interface explains the set of properties and methods that an object must be treated as "duck-typed" for a specific purpose.

Benefits of duck typing

One of the main benefits of duck typing is making code more flexible and reusable. The code works for any object with the required methods and properties, not just specific types of objects, and can be used in a variety of situations without modification. Duck typing also improves code reuse by enabling interchangeable use of objects of different types within a single code base.

An example of duck typing is TypeScript

The following is an example of how to use duck typing in TypeScript -

Define an interface to represent the behavior you want your object to have. For example -

interface Duck {
   quack(): void;
}

Create a class that implements this interface. For example -

class MallardDuck implements Duck {
   quack(): void {
      console.log("Quack!");
   }
}

Create an instance of this class and use it as the type defined by the interface.

let duck: Duck = new MallardDuck();
duck.quack(); // Output: "Quack!"

Create another class that also implements this interface -

class RubberDuck implements Duck {
   quack(): void {
      console.log("Squeak!");
   }
}

Use the new class instance as the same type defined by the interface.

let duck: Duck = new RubberDuck();
duck.quack(); // Output: "Squeak!"

As you can see, both the MallardDuck and RubberDuck classes implement the Duck interface, and duck variables can be assigned to instances of both classes. The type is determined by the interface rather than the behavior (methods and properties) defined in the class.

Also note that in TypeScript you can use the typeof keyword to check the type of an object at runtime and whether the object has the expected method or property.

Example

In this example, the Bird and Plane classes implement the Flyable interface, which requires the Fly() method. Both "duck typing" can be used interchangeably in the goFly() function. The function doesn't care about the actual type of the object passed to it, as long as it has a fly() method that can be called.

interface Flyable {
   fly(): void;
}

class Bird implements Flyable {
   fly(): void {
      console.log("Bird is flying");
   }
}

class Plane implements Flyable {
   fly(): void {
      console.log("Plane is flying");
   }
}

function goFly(flyable: Flyable) {
   flyable.fly();
}

let bird = new Bird();
let plane = new Plane();

goFly(bird); // Prints "Bird is flying"
goFly(plane); // Prints "Plane is flying"

When compiled, it will generate the following JavaScript code -

var Bird = /** @class */ (function () {
   function Bird() {
   }
   Bird.prototype.fly = function () {
      console.log("Bird is flying");
   };
   return Bird;
}());
var Plane = /** @class */ (function () {
   function Plane() {
   }
   Plane.prototype.fly = function () {
      console.log("Plane is flying");
   };
   return Plane;
}());
function goFly(flyable) {
   flyable.fly();
}
var bird = new Bird();
var plane = new Plane();
goFly(bird); // Prints "Bird is flying"
goFly(plane); // Prints "Plane is flying"

Output

The above code will produce the following output -

Bird is flying
Plane is flying

Example

Overall, duck typing is a powerful programming concept that allows objects of different types to be used interchangeably as long as they have the same methods and properties, thus providing greater flexibility and reusability in TypeScript code. sex. In this example, the Driveable interface, Car and Truck classes display the same content.

interface Driveable {
  drive(): void;
}

class Car implements Driveable {
  drive(): void {
    console.log("Car is driving");
  }
}

class Truck implements Driveable {
  drive(): void {
    console.log("Truck is driving");
  }
}

function goDrive(driveable: Driveable) {
  driveable.drive();
}

let car = new Car();
let truck = new Truck();

goDrive(car); // Prints "Car is driving"
goDrive(truck); // Prints "Truck is driving"

When compiled, it will generate the following JavaScript code -

var Car = /** @class */ (function () {
    function Car() {
    }
    Car.prototype.drive = function () {
        console.log("Car is driving");
    };
    return Car;
}());
var Truck = /** @class */ (function () {
    function Truck() {
    }
    Truck.prototype.drive = function () {
        console.log("Truck is driving");
    };
    return Truck;
}());
function goDrive(driveable) {
    driveable.drive();
}
var car = new Car();
var truck = new Truck();
goDrive(car); // Prints "Car is driving"
goDrive(truck); // Prints "Truck is driving"

Output

The above code will produce the following output -

Car is driving
Truck is driving

The main idea behind duck typing is that code should be written to work with any object that has the required methods and properties, rather than being written to work with a specific object. This makes your code more flexible and reusable, allowing you to use different types of objects interchangeably without changing your code.

The above is the detailed content of Duck types in TypeScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete