本篇将介绍TypeScript里的类和接口。

与其他强类型语言类似,TypeScript遵循ECMAScript 2015标准,支持class类型,同时也增加支持interface类型。

一、类(class)

下面是一个类的基本定义方式:

 class User {
name: string;
constructor(_name: string) {
this.name = _name;
} sayHello(): string {
return `Hello,${this.name}!`;
}
} let user = new User('John Reese');
user.sayHello();

在上面的例子里,定义了一个类User,这个类拥有一个属性、一个构造函数和一个实例方法sayHello。通过new的方式,可以用这个类实例化一个实例对象,并可以调用实例方法。这与大多数静态语言的声明方式一致。

1. 类成员的访问级别

与强类型语言类似,TypeScript的类成员可以显式声明访问级别:public、protected、private

 class User {
name: string;
private sex: string;
protected age: number;
constructor(_name: string) {
this.name = _name;
} sayHello(): string {
return `Hello,${this.name}!`;
}
} let user = new User('John Reese');
user.name = 'Root'; // 公有属性,可以赋值
user.sex = 'female'; // 私有属性,无法赋值
user.age = 28; // 受保护属性,无法赋值
user.sayHello();

在TypeScript里,如果不显示指定访问级别,则默认为public。

2. 属性的get和set访问器

 class User {
private _name: string; get name(): string {
return this._name;
} set name(newName: string) {
this._name = newName;
} constructor(_name: string) {
this.name = _name;
} sayHello(): string {
return `Hello,${this._name}!`;
}
} let user = new User('John Reese');
user.name = 'Root';
user.sayHello();

通过get和set关键字声明属性访问器,通过属性访问器可以精确控制属性的赋值和获取值。下面是经过编译后生成的JavaScript代码

 var User = (function () {
function User(_name) {
this.name = _name;
}
Object.defineProperty(User.prototype, "name", {
get: function () {
return this._name;
},
set: function (newName) {
this._name = newName;
},
enumerable: true,
configurable: true
});
User.prototype.sayHello = function () {
return "Hello," + this._name + "! " + this._age;
};
return User;
}());
var user = new User('John Reese');
user.name = 'Root';
user.sayHello();

3. 静态属性

静态属性即是通过类型而不是实例就可以访问的属性

 class User {
static sex_type = ['male', 'female']; // 静态属性
name: string;
sex: string; constructor(_name: string) {
this.name = _name;
} sayHello(): string {
return `Hello,${this.name}!`;
}
} let user = new User('John Reese');
user.name = 'Root';
user.sex = User.sex_type[1];
user.sayHello();

通过static关键字可以声明类型的静态属性。

4. 类的继承

同强类型语言一样,TypeScript也支持类的继承

 // 基类
class Animal {
name: string; constructor(theName: string) {
this.name = theName;
} eat() {
console.log(`${this.name} 吃食物。`);
}
} // 子类继承基类
class Dog extends Animal {
constructor(theName: string) {
super(theName);
} eat() {
super.eat();
console.log('并且吃的是狗粮。');
}
} class People extends Animal {
constructor(theName: string) {
super(theName);
} // 子类重写基类方法
eat() {
console.log(`${this.name} 拒绝吃狗粮。`);
}
} let animal = new Animal('动物');
animal.eat(); let dog: Animal;
dog = new Dog('狗');
dog.eat(); let people: Animal;
people = new People('人类');
people.eat();

从上面的例子可以看到,子类通过extends关键字可以继承其他类,通过super方法调用基类对应的方法,也可以直接重写基类的方法。

下面是编译之后生成JavaScript源码,可以比较看看

 var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
// 基类
var Animal = (function () {
function Animal(theName) {
this.name = theName;
}
Animal.prototype.eat = function () {
console.log(this.name + " \u5403\u98DF\u7269\u3002");
};
return Animal;
}());
// 子类继承基类
var Dog = (function (_super) {
__extends(Dog, _super);
function Dog(theName) {
_super.call(this, theName);
}
Dog.prototype.eat = function () {
_super.prototype.eat.call(this);
console.log('并且吃的是狗粮。');
};
return Dog;
}(Animal));
var People = (function (_super) {
__extends(People, _super);
function People(theName) {
_super.call(this, theName);
}
// 子类重写基类方法
People.prototype.eat = function () {
console.log(this.name + " \u62D2\u7EDD\u5403\u72D7\u7CAE\u3002");
};
return People;
}(Animal));
var animal = new Animal('动物');
animal.eat();
var dog;
dog = new Dog('狗');
dog.eat();
var people;
people = new People('人类');
people.eat();

编译之后的JavaScript源码

5. 抽象类

将上面的例子稍微修改下

 // 抽象类
abstract class Animal {
name: string; constructor(theName: string) {
this.name = theName;
} abstract eat();
} // 子类继承抽象类
class Dog extends Animal {
constructor(theName: string) {
super(theName);
} eat() {
console.log(`${this.name} 吃狗粮。`);
}
} let animal = new Animal('动物'); // 抽象类无法实例化
animal.eat(); let dog: Animal;
dog = new Dog('狗');
dog.eat();

通过abstract关键字声明抽象类和抽象方法,子类继承抽象类后,需要实现抽象方法。同样的,抽象类不能被实例化。

二、接口

下面是一个简单的接口声明

 interface Animal {
name: string;
}

在JavaScript里没有对应的类型与之对应,所以编译之后不会生成任何JavaScript代码。

1. 作为参数类型

接口类型可以作为方法的参数类型,效果等同于直接指定Json对象的类型。

 interface Animal {
name: string;
} let printName = function(param: Animal) {
console.log(`Name is ${param.name}`);
} printName({name: 'Dog'});

同样,接口成员也可以是缺省的

 interface Animal {
name: string;
age?: number;
} let printName = function (param: Animal) {
if (param.age) {
console.log(`Name is ${param.name}, and age is ${param.age}`);
} else {
console.log(`Name is ${param.name}`);
}
} printName({ name: 'Dog' });
printName({ name: 'Dog', age: 5 });

但是在某些情况下,调用方法时,参数赋值可能会有多个,接口在作为参数类型时也支持拥有多个成员的情况。

 interface Animal {
name: string;
age?: number;
[propName: string]: any; // 其他成员
} let printName = function (param: Animal) {
if (param.age) {
console.log(`Name is ${param.name}, and age is ${param.age}`);
} else {
console.log(`Name is ${param.name}`);
}
} printName({ name: 'Dog' });
printName({ name: 'Dog', age: 5 });
printName({ name: 'Dog', age: 5, character: '粘人' }); // 多于明确定义的属性个数

2. 作为其他类型

接口也可以定义方法的类型,和数组类型

 interface FuncType {
(x: string, y: string): string; // 声明方法成员
} let func1: FuncType;
func1 = function (prop1: string, prop2: string): string { // 方法参数名称不需要与接口成员的参数名称保持一致
return prop1 + ' ' + prop2;
} interface ArrayType {
[index: number]: string; // 声明数组成员
} let arr: ArrayType;
arr = ['Dog', 'Cat'];

3. 接口的继承与实现

同强类型语言一样,TypeScript的接口支持继承与实现。

 interface Animal {
name: string;
eat(): void;
} class Dog implements Animal {
name: string;
constructor(theName: string) {
this.name = theName;
} eat() {
console.log(`${this.name} 吃狗粮。`)
}
} class Cat implements Animal {
name: string;
constructor(theName: string) {
this.name = theName;
} eat() {
console.log(`${this.name} 吃猫粮。`)
}
} let dog: Animal;
dog = new Dog('狗狗');
dog.eat(); let cat: Animal;
cat = new Cat('喵星人');
cat.eat();

类通过implements关键字继承接口,并实现接口成员。

同时,接口也可以多重继承。

 interface Animal {
name: string;
eat(): void;
} interface Person extends Animal { // 继承自Animal接口
use(): void;
} class People implements Person {
name: string;
constructor(theName: string) {
this.name = theName;
} eat() {
console.log(`${this.name} 拒绝吃狗粮。`)
} use() {
console.log(`${this.name} 会使用工具。`)
}
} let man: Person;
man = new People('男人');
man.eat();
man.use();

4. 类型转换

在TypeScript里,接口可以对符合任一成员类型的对象进行转换,转换之后的对象自动继承了接口的其他成员。

 interface Animal {
name: string;
age: number;
eat(): void;
} let thing = { name: '桌子' };
let otherThing = <Animal>thing; // 类型转换
otherThing.age = 5;
otherThing.eat = function () {
console.log(`${this.name} 不知道吃什么。`)
};

上面的例子里,声明了拥有name属性的json对象,通过<>将json对象转换成了Animal类型的对象。转换后的对象则拥有了另外的age属性和eat方法。

5. 接口继承类

在TypeScript里,接口可以继承类,这样接口就具有了类里的所有成员,同时这个接口只能引用这个类或者它的子类的实例。

 class People {
name: string;
private age: number;
constructor(theName: string) {
this.name = theName;
} eat() {
console.log(`${this.name} 拒绝吃狗粮。`);
} use() {
console.log(`${this.name} 会使用工具。`)
}
} interface Animal extends People { // 接口 } class Man extends People { // 子类 } class Cat { // 拥有同样结构的另外一个类
name: string;
private age: number;
constructor(theName: string) {
this.name = theName;
} eat() {
// 具体实现
} use() {
// 具体实现
}
} let cat: Animal;
cat = new Cat('喵星人'); // Cat类不是People的子类,无法被Animal引用 let man: Animal;
man = new Man('男人');
man.eat();

当继承链过深,代码需要在某一个子类的类型下执行时,这种方法比较有效。

TypeScript学习笔记(四) - 类和接口的更多相关文章

  1. Typescript 学习笔记四:回忆ES5 中的类

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  2. typescript学习笔记(三)---接口

    关于第二章的学习笔记是变量声明. 接口:TypeScript的核心原则之一是对值所具有的结构进行类型检查. 它有时被称做“鸭式辨型法”或“结构性子类型化”. 在TypeScript里,接口的作用就是为 ...

  3. 初探swift语言的学习笔记四(类对象,函数)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/29606137 转载请注明出处 假设认为文章对你有所帮助,请通过留言 ...

  4. [Scala]Scala学习笔记四 类

    1. 简单类与无参方法 class Person { var age = 0 // 必须初始化字段 def getAge() = age // 方法默认为公有的 } 备注 在Scala中,类并不声明为 ...

  5. Typescript 学习笔记六:接口

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  6. Typescript 学习笔记五:类

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  7. Typescript 学习笔记七:泛型

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  8. Typescript 学习笔记二:数据类型

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  9. Typescript 学习笔记三:函数

    中文网:https://www.tslang.cn/ 官网:http://www.typescriptlang.org/ 目录: Typescript 学习笔记一:介绍.安装.编译 Typescrip ...

  10. Typescript 学习笔记一:介绍、安装、编译

    前言 整理了一下 Typescript 的学习笔记,方便后期遗忘某个知识点的时候,快速回忆. 为了避免凌乱,用 gitbook 结合 marketdown 整理的. github地址是:ts-gitb ...

随机推荐

  1. navicat链接mysql

    navicat链接mysql

  2. P3097 [USACO13DEC]最优挤奶Optimal Milking

    P3097 [USACO13DEC]最优挤奶Optimal Milking 题意简述:给定n个点排成一排,每个点有一个点权,多次改变某个点的点权并将最大点独立集计入答案,输出最终的答案 感谢@zht4 ...

  3. Java基础-Calendar类常用方法介绍

    Java基础-Calendar类常用方法介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Calendar类概念 Calendar 类是一个抽象类,它为特定瞬间与一组诸如 Y ...

  4. JSP中九大内置对象+request对象的属性介绍和如何应用

    JSP的九大内置对象requestresponseApplicationconfigoutpagepageContextsessionException默认没有,需要进行在Page指令下进行isErr ...

  5. CF&&CC百套计划1 Codeforces Round #449 B. Ithea Plays With Chtholly

    http://codeforces.com/contest/896/problem/B 题意: 交互题 n张卡片填m个1到c之间的数,1<=n*ceil(c/2)<=m 最后填出一个单调非 ...

  6. 《设计模式》-原则三:依赖倒置原则(DIP)

    这几天晚上回来都去玩了!没有坚持学习.真的好惭愧! 非常自责 后面一定要坚持 一气呵成  争取每天学一点,把这个学完. 今天主要是看了一下  设计模式中的 原则三: 依赖倒置原则(DIP) 官方是这样 ...

  7. 20155227 2016-2017-2 《Java程序设计》第七周学习总结

    20155227 2016-2017-2 <Java程序设计>第七周学习总结 教材学习内容总结 认识时间与日期 时间的度量 世界时:在1972年引入UTC之前,GMT与UT是相同的. 国际 ...

  8. Linux基础-host文件解析

    任务目标:为集群内的机器设定主机名,利用/etc/hosts文件来解析自己的集群中所有的主机名, 相应的集群的配置应该改成使用主机名的方式 使用 hostnamectl set-hostname 设定 ...

  9. Linux的基础优化

    归结成口诀: 一清.一精.一增.两优.四设.七其他 一清: 定时清理日志 一精: 精简开机启动服务 一增: 增大文件描述符 两优: linux内核参数的优化.yum源优化 四设:设置系统的字符集.设置 ...

  10. Django 使用mysql 所遇到问题一:Error loading MySQLdb module

    在配置完mysql 的配置信息后执行 python manage.py runserver 时出现如下错误.(py3的环境) 解决 在 python2 中,使用 pip install mysql-p ...