转载node
项目实践仓库git
https://github.com/durban89/typescript_demo.git tag: 1.1.0
为了保证后面的学习演示须要安装下ts-node,这样后面的每一个操做都能直接运行看到输出的结果。github
npm install -D ts-node
后面本身在练习的时候能够这样使用typescript
npx ts-node 脚本路径
在TypeScript里,咱们可使用经常使用的面向对象模式。 基于类的程序设计中一种最基本的模式是容许使用继承来扩展示有的类。看下面的例子:npm
class Animal { move(distanceMeter: number = 0) { console.log(`Animal moved ${distanceMeter}m`); } } class Dog extends Animal { bark() { console.log('Woof........!'); } } const dog = new Dog(); dog.bark(); dog.move(3); dog.bark();
运行后获得以下结果函数
$ npx ts-node src/classes_2.ts Woof........! Animal moved 3m Woof........!
这个例子展现了最基本的继承:类从基类中继承了属性和方法。这里,Dog是一个派生类,它派生自Animal基类,经过extends关键字。派生类一般被称做 子类,基类一般被称做超类。学习
由于Dog继承了Animal的功能,所以咱们能够建立一个Dog的实例,它可以 bark()和move()。下面咱们来看个更加复杂的例子。this
class Animal { name: string; constructor(theName: string) { this.name = theName; } move(distanceMeter: number = 0) { console.log(`${this.name} moved ${distanceMeter}m`); } } class Snake extends Animal { constructor(name: string) { super(name); } move(distanceMeter: number = 5) { console.log('滑动的声音......'); super.move(distanceMeter); } } class Horse extends Animal { constructor(name: string) { super(name); } move(distanceMeter: number = 45) { console.log('跑动的声音......'); super.move(distanceMeter); } } const snake = new Snake('small snake'); const horse: Animal = new Horse('small horse'); snake.move(); horse.move(152);
运行后获得以下结果spa
$ npx ts-node src/classes_2.ts 滑动的声音...... small snake moved 5m 跑动的声音...... small horse moved 152m
这个例子展现了一些上篇文章【TypeScript基础入门 - 类 - 简介】没有提到的特性。 这一次,咱们使用extends关键字建立了 Animal的两个子类:Horse和 Snake。设计
与前一个例子的不一样点是,派生类包含了一个构造函数,它必须调用super(),它会执行基类的构造函数。 并且,在构造函数里访问this的属性以前,咱们必定要调用 super()。 这个是TypeScript强制执行的一条重要规则。
这个例子演示了如何在子类里能够重写父类的方法。Snake类和 Horse类都建立了move方法,它们重写了从Animal继承来的move方法,使得 move方法根据不一样的类而具备不一样的功能。注意,即便horse被声明为Animal类型,但由于它的值是Horse,调用tom.move(152)时,它会调用Horse里重写的方法。
本实例结束实践项目地址
https://github.com/durban89/typescript_demo.git tag: 1.1.1