TypeScript 鸭子打字
在 TypeScript 编程中,duck-typing 特性确保了类型安全。作为鸭子类型规则的结果,TypeScript 编译器验证两个对象是否相同。
TypeScript 中的鸭子类型技术用于通过确定它们是否具有相同的类型匹配属性和对象成员来比较两个对象。例如,如果我们为一个对象分配了两个属性和一个方法,而第二个对象只分配了两个属性。当我们创建 object1 的变量并为其分配第二个对象类型的变量时,打字稿编译器会在这种情况下引发编译时错误。让我们通过一个例子来理解运气打字。
示例 1:在下面的代码中,我们创建了三个类:鸽子、企鹅和猫头鹰。这三个类都有一个称为“声音”的属性。 Penguin 类有一个额外的方法,称为游泳。当我们将 owl 分配给 penguin 变量时,它不会出错,因为它们都具有相同的属性。将鸽子分配给 owl 类型变量或将企鹅对象分配给 pigeon 类型变量时也是如此。但是我们不能将鸽子类型的对象分配给企鹅,因为企鹅有一个额外的类方法,而鸽子没有。
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);
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();
输出:当我们编译.ts文件时,我们得到这个错误:
error TS2741: Property ‘swim’ is missing in type ‘Pigeon’ but required in type ‘Penguin’.
let penguin: Penguin = new Pigeon();
当我们使用命令运行.js文件时:
node filename.js
输出:
A pigeon hoots
An owl coos
A pigeon peeps
A penguin coos
示例 2:在此示例中,我们创建了两个类 normal_phone 和 iPhone。这个例子只是为了更好地理解。普通手机和 iPhone 都可以帮助用户打电话和发短信,在示例中 iPhone 有一个方法 camera_experience()。所以 iPhone 包含了普通手机的所有功能,而且它有一个很好的摄像头。因此,如果我们创建一个 iPhone 类型的变量并传递 normal_phone 对象,它将起作用,但相反是不可能的,因为 normal_phone 不包含 camera_experience() 方法。
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();
输出:编译.ts文件后,我们得到这个错误:
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.
当我们使用命令运行.js文件时:
node filename.js
输出:
[ 'calls', 'messages' ]
i am very well known for my camera
undefined
参考: https://www.typescriptlang.org/docs/handbook/interfaces.html