class Animal {
public name: string;
// 静态属性
static categories: string [] = ['mammal', 'bird']
// 静态方法
static isAnimal(a) {
return a instanceof Animal
}
// 构造方法
constructor(name: string) {
this.name = name
}
run() {
return `${this.name} is running`
}
}
console.log(Animal.categories) // ['mammal', 'bird']
const snake = new Animal('lily') // lily is running
console.log(Animal.isAnimal(snake)) // true
class Dog extends Animal {
bark() {
return `${this.name} is barking`
}
}
const xiaobao = new Dog('xiaobao')
console.log(xiaobao.run()) // xiaobao is running
console.log(xiaobao.bark()) // xiaobao is barking
class Cat extends Animal {
constructor(name) {
super(name)
console.log(this.name)
}
// 重写父类方法
run() {
return 'Meow, ' + super.run()
}
}
const miaomiao = new Cat()
console.log(maomao.run()) // miaomiao Meow, maomao is running
接口:interface
对对象的约束
interface Person {
readonly id: number;
name: string;
age ?: number;
}
let viking: Person = {
id: 123.
name: 'hebe'
}
对类的扩展
当公共属性和方法不方便抽成一个类时,可以使用接口进行抽象
接口之间也是可以继承的
interface Radio {
switchRadio() : void;
}
interface Battery {
checkBatteryStatus();
}
interface RadioWithBattey extends Radio {
checkBatteryStatus();
}
class Car implements Radio , Battery {
switchRadio() { };
checkBatteryStatus() { };
}
class Cellphone implements RadioWithBattey {
switchRadio() { };
checkBatteryStatus() { };
}
枚举
const enum Direction {
Up = 'UP',
Down = 'DOWN',
Left = 'LEFT',
Right = 'RIGHT'
}
// console.log(Direction.Up) // 0
// console.log(Direction[0]) // Up
const value = 'UP'
if (value === Direction.Up) {
console.log('Go Up!')
}