本文为个人学习摘要笔记。
原文地址:TypeScript 高级类型及用法
interface Ant {
name: string
weight: number
}
interface Fly {
flyHeight: number
speed: number
}
// 少了任何一个属性都会报错
const flyAnt: Ant & Fly = {
name: '蚂蚁呀嘿',
weight: 0.2,
flyHeight: 20,
speed: 1,
}
class Bird {
fly() {
console.log('Bird flying')
}
layEggs() {
console.log('Bird layEggs')
}
}
class Fish {
swim() {
console.log('Fish swimming')
}
layEggs() {
console.log('Fish layEggs')
}
}
const bird = new Bird()
const fish = new Fish()
function start(pet: Bird | Fish) {
// 调用 layEggs 没问题,因为 Bird 或者 Fish 都有 layEggs 方法
pet.layEggs()
// 会报错:Property 'fly' does not exist on type 'Bird | Fish'
// pet.fly();
// 会报错:Property 'swim' does not exist on type 'Bird | Fish'
// pet.swim();
}