基本用法
先来看一个简单的typescript类的用法
class Person {
name: string
gender: string
age: number
constructor (name: string, gender: string, age: number) {
this.name = name
this.gender = gender
this.age = age
}
run (): void {
console.log(`${this.name} is running`)
}
}
const jack = new Person('jack', 'male', 18)
jack.run() //jack is running
可以看到上面的例子中,类的用法基本和es6中的类没啥区别,我们需要重点注意点是继承和es6中没有提供的修饰符。
继承
class Pat {
name: string
constructor (name: string) {
this.name = name
}
eat (): void {
console.log(`${this.name} is eating`)
}
}
class Cat extends Pat {
color: string
constructor (name: string, color: string) {
//必须调用super方法,否则typescript将报错
super(name)
//添加子类独有的变量
this.color = color
}
move (): void {
console.log(`${this.name} is moving`)
}
}
const Bobi = new Cat('Bobi', 'white')
Bobi.eat() //Bobi is eating
Bobi.move() //Bobi is moving
值得注意的点是,如果我们在用extends关键字继承了某一个类,那么我们必须在子类中用super(params)的形式调用父类的构造函数,否则typescript将报错。这样做可以保证所有需要挂载到子类实例的变量都挂载到实例中。除此之外也可以在子类构造函数中添加自己独有的变量。
除此之外,在子类中重复声明从父类中继承过来的属性和方法时,子类将会覆盖父类。
静态变量(Statics)
class Pat {
name: string
constructor (name: string) {
this.name = name
}
eat (): void {
console.log(`${this.name} is eating`)
}
static staticMethod (): void {
console.log('it is a static method, can only accessed by the class itself')
}
}
class Cat extends Pat {
color: string
constructor (name: string, color: string) {
super(name)
this.color = color
}
move (): void {
console.log(`${this.name} is moving`)
}
}
const Bobi = new Cat('Bobi', 'white')
const Tom = new Pat('Tom')
Pat.staticMethod()
Cat.staticMethod()
Bobi.staticMethod() //报错
Tom.staticMethod() //报错
在上面的代码中,我们在父类Pat中定义了一个静态方法staticMethod,运行之后可以发现只能在父类或者子类本身才可以成功访问该方法,否则将报错,还有一个可以访问静态属性或者方法的地方就是类内部,请看以下代码
class Something {
static instances = 0;
constructor() {
Something.instances++;
}
}
var s1 = new Something();
var s2 = new Something();
console.log(Something.instances); //2
访问修饰符
typescript提供了三种修饰符,分别是public,protected,private,分别的访问权限如下表所示
当没有使用任何修饰符是,变量权限默认为public。
值得注意的点时,在生成的js代码中,无论我们在什么地方访问protected或者private变量都可以正常运行,但是typescript会给出一个编译时错误。以确保让我们正确使用这些修饰符请看以下代码
class FooBase {
public x: number;
private y: number;
protected z: number;
}
// EFFECT ON INSTANCES
var foo = new FooBase();
foo.x; // okay
foo.y; // ERROR : private
foo.z; // ERROR : protected
// EFFECT ON CHILD CLASSES
class FooChild extends FooBase {
constructor() {
super();
this.x; // okay
this.y; // ERROR: private
this.z; // okay
}
}
部分代码示例,以及修饰符表格来自 TypeScript Deep Dive Basarat AliSyed著