一、接口
1. 接口的定义
我们在其他语言中如:c++, java, python等语言接口我们会花大量时间去学习,但在TS中,我们不需要花费太多的时间在接口上,他没有上述语言中接口这么难理解和使用,大家在学习TS中的接口时可以想着”此接口非彼接口”,简单的来说TS中的类是用来描述一个类型
下面来看看在代码中的定义吧:
定义接口需要使用关键字:interface
//定义接口类型 | |
interface Employee { | |
name: string, | |
salary: number | |
} |
这就是一个简单的接口
下面我们来看看如何来使用这个接口吧!
const em1:Employee = { | |
name:'jhon', | |
salary: 123, | |
} | |
const em2: Employee = { | |
name: 'ice_moss', | |
salary: 8000, | |
} | |
console.log(em2, em1) |
输出结果:
{ | |
"name": "ice_moss", | |
"salary": 8000, | |
}, { | |
"name": "jhon", | |
"salary": 12000 | |
} |
我们定义了一个接口Employee,接着定义了变量em1和em2他们的类型是Employee,使用em1和em2实现了Employee的属性和方法,我们称em1和em2实现了Employee的接口
2. 接口的语法
上面的实例中我们只在接口中描述了属性,下面我们将属性和方法一起实现:
//定义接口类型 | |
interface Employee { | |
name: string | |
salary: number | |
bonus?: number | |
getIncom():number | |
} | |
const em1:Employee = { | |
name:'jhon', | |
salary: 12000, | |
bonus: 2000, | |
getIncom(){ | |
return this.salary | |
} | |
} | |
const em2: Employee = { | |
name: 'ice_moss', | |
salary: 8000, | |
bonus: 3000, | |
getIncom(){ | |
return this.salary + (this.bonus || 0) | |
} | |
} |
3. 接口的高级用法
3. 1可选参数串联
interface Employee { | |
name?:{ //可选参数 | |
first?: string //可选参数 | |
last: string | |
} | |
salary: number | |
bonus?: number | |
} | |
//寻找可选参数 | |
function hasBadName(e: Emplotee){ | |
if(name){ | |
if(name.first){ | |
name.fisrt.startWith('AAA') | |
} | |
} | |
} |
这样看着就比较复杂,我们有简单的方法:
function hasBadName(e: Employee){ | |
return e.name?.first?.startsWith('AAA') | |
} | |
//解释:第一步判断e.name是否存在,不存在则返回undefined;如果存在e.name继续以此方式向下判断 |
来看看具体的用法:
interface Employee { | |
name?: { | |
last?: string, | |
first?: string, | |
} | |
salary: number | |
bonus?: number | |
} | |
function hasBadName(e: Employee){ | |
return e.name?.first?.startsWith('AAA') | |
} | |
console.log(hasBadName({ | |
name:{ | |
first: 'jhon', | |
last: 'smith', | |
}, | |
salary: 8000, | |
})) | |
//输出:false | |
console.log(hasBadName({ | |
name:{ | |
last: 'smith', | |
}, | |
salary: 8000, | |
})) | |
//输出:undefined |
这样我们就可以保护我们的程序不会挂掉
3. 2非空断言
在可选参数串联中,我们不能根本解决问题,所以我们需要使用!
来非空断言
只需要将3.1中的?
给为!
即可。
3. 3接口的拓展
我们可以理解为面向对象语言中的继承,老接口我们可以理解为父亲接口,新的接口我们理解为叫儿子接口为,儿子接口通过关键字extends
继承父亲接口的属性和方法
实例:
//儿子接口 | |
interface Employee extends HasName { //接口的拓展:extends | |
salary: number | |
bonus?: number | |
} | |
//父亲接口 | |
interface HasName{ | |
name: { | |
last: string, | |
first: string, | |
} | |
} | |
//em1实现了接口Employee | |
const em1: Employee = { | |
name:{ | |
first:'_moss', | |
last: 'ice' | |
}, | |
salary: 20000, | |
bonus: 1000 | |
} | |
console.log(em1) |
输出结果:
{ | |
"name": { | |
"first": "_moss", | |
"last": "ice" | |
}, | |
"salary": 20000, | |
"bonus": 1000 | |
} |
3. 4接口的并和类型断言
3.4.1接口的并
这里的“并”其实更像我们数学中的“交”
//接口的并和类型断言 | |
//假设这是一个按钮 | |
interface WxButton{ | |
visible: boolean, | |
enabled:boolean, | |
onClick():void, | |
} | |
//假设这是一个图片 | |
interface WxImage{ | |
visible: boolean, | |
src: string, | |
withd:number, | |
heigth: number, | |
} | |
这里可以看出来这里的”并”其实取两接口类型的公有部分
3.4.2类型断言
//接口的并和类型断言 | |
interface WxButton{ | |
visible: boolean, | |
enabled:boolean, | |
onClick():void, | |
} | |
interface WxImage{ | |
visible: boolean, | |
src: string, | |
withd:number, | |
heigth: number, | |
} | |
//类型断言 | |
function processElement(e: WxButton | WxImage){ | |
if((e as any).onClick){ | |
const btn = e as WxButton | |
btn.onClick() | |
}else{ | |
const img = e as WxImage | |
console.log(img.src) | |
} | |
} | |
processElement({ | |
visible: true, | |
src: 'this is src', | |
withd: 20, | |
heigth: 30, | |
}) | |
processElement({ | |
visible: true, | |
enabled: true, | |
onClick(){ | |
console.log('onClick') | |
} | |
}) | |
//输出结果: | |
// "this is src" | |
// "onClick" |
二、类
1.类的定义
类描述了所创建的对象共同的属性和方法。
TypeScript 支持面向对象的所有特性,比如 类、接口等。
TypeScript 类定义方式如下:
class class_name { | |
//作用域 | |
} |
类有三个重要的模块:
- 属性:
- 字段是类声明的变量。
- 构造函数:
- 类实例化时调用,可以为类的对象分配内存。
- 方法:
- 方法为对象要执行的操作。
1.1类的属性(字段)
class Employee { | |
name: string = 'ice_moss' //这里需要注意类字段需要给初始化 | |
salary: number = 20000 | |
} |
1.2构造函数
我们声明一个Employee
l类,构造函数在实例中初始化了类的字段name和salary,构造函数在初始化的时候使用关键字this
:表示在该类下的字段
class Employee { | |
name: string = 'ice_moss' | |
salary: number = 20000 | |
constructor(name: string, salary: number){ | |
this.name = name | |
this.salary = salary | |
} | |
} | |
//当然,我们在可以在构造函数中使用关键字public,然后就可以不用在单独声明字段了: | |
class Employee { | |
constructor(public name: string, public salary: number){ | |
this.name = name | |
this.salary = salary | |
} | |
//这样看着会更简洁 | |
//其实这里还可以将直接写成: | |
class Employee { | |
constructor(public name: string, public salary: number){} |
1.3方法
class Employee { | |
constructor(public name: string, public salary: number){ | |
this.name = name | |
this.salary = salary | |
} | |
getName():void{ //获取name | |
console.log(this.name) | |
} | |
getSalary():void{ //获取salary | |
console.log(this.salary) | |
} | |
} |
2.类的实例化
var object_name = new class_name([ arguments ])
依然是Employee类
class Employee { | |
constructor(public name: string, public salary: number){ | |
this.name = name | |
this.salary = salary | |
} | |
getName():void{ //获取name | |
console.log(this.name) | |
} | |
getSalary():void{ //获取salary | |
console.log(this.salary) | |
} | |
} | |
//类的实例,需要使用关键字"new" | |
const em = new Employee('jhon', 9000) | |
console.log(em) | |
em.getName() | |
em.getSalary() | |
//输出结果: | |
Employee: { | |
"name": "jhon", | |
"salary": 9000 | |
} | |
"jhon" | |
9000 |
3.访问控制修饰符
TypeScript 中,可以使用访问控制符来保护对类、变量、方法和构造方法的访问。TypeScript 支持 3 种不同的访问权限。
public(默认) : 公有,可以在任何地方被访问。
protected : 受保护,可以被其自身以及其子类和父类访问。
private : 私有,只能被其定义所在的类访问。
下面继续看实例:
class Employee{ | |
private allocatebonus?: number //allocatebonus是私有属性同时也是可选参数 | |
private bonus: number = 0 | |
constructor(public name:string, public salary:number){ | |
this.name = name | |
this.salary = salary | |
} |

此时我们在实例中是访问不到allocatebonus和bonus
3. getter/setter
我们在类中可以将函数写成调用字段的形式
class Employee{ | |
private allocatebonus?: number | |
constructor(public name:string, public salary:number){ | |
} | |
set bonus(v: number){ | |
this.allocatebonus = v | |
} | |
get bonus(){ | |
return this.allocatebonus || 0 | |
} | |
} |
实例化:
const em = new Employee('jhon', 9000) | |
em.bonus = 2000 | |
console.log(em) |
输出:
Employee: { | |
"name": "jhon", | |
"salary": 9000, | |
"allocatebonus": 2000 | |
} |
4.类的继承(继承类的方法重写)
类的继承和接口的拓展相似,我们可以理解为面向对象语言中的继承,旧的类我们称为父类,新的类我们称为子类为,子类通过关键字extends
继承父类的属性和方法
类继承后,子类可以对父类的方法重新定义,这个过程称之为方法的重写。
其中 super 关键字是对父类的直接引用,该关键字可以引用父类的属性和方法。
//父类 | |
class Employee{ | |
private allocatebonus?: number | |
constructor(public name:string, public salary:number){ | |
} | |
set bonus(v: number){ | |
this.allocatebonus = v | |
} | |
get bonus(){ | |
return this.allocatebonus || 0 | |
} | |
} | |
//子类 | |
class Manager extends Employee{ | |
private reporters: Employee[] | |
constructor(name:string, salary:number) { | |
super(name, salary) | |
this.reporters = [] | |
} | |
addReporters(e: Employee){ | |
this.reporters.push(e) | |
} | |
} | |
const manager = new Manager('DF', 200000) |
当类继承成功后我们可以看到如图:

三、用类实现接口
在前面两部分的内容学习后,我们现在可以使用类来实现接口了,先来看看简单的实现:
1. 接口隐式实现
//接口 | |
interface Emploeey{ | |
name: string | |
salary: number | |
} | |
//类 | |
class Emplmpl{ | |
name: string | |
salary: number | |
constructor( name:string, salary:number){ //构造函数 | |
this.name = name | |
this.salary = salary | |
} | |
} | |
//这里我们可能不能直接看出类是如何实现接口的,在TS中我们只要类满足了接口的属性和方法,也就是类实现了该接口 | |
const emplpml = new Emplmpl('ice_moss', 10000) | |
这样接口就被类实现了,当然这里也可以这要声明一下:
const emplpml = new Emplmpl('ice_moss', 10000) | |
const em1: Emploeey = emplpml |
这里总结一下:我们使用上面的这种实现属于隐式实现,当问你赋值后编译器会逐一去比较接口和类中的字段;但是这里同样也有一个问题,如果我们在类中少了接口中的属性或者方法,使用隐式实现的方法则可能不能实现该接口,但编译器不会提醒我们。
2. 接口的显示实现
我们使用类来实现接口也可以使用显示实现,这种实现方式可以将实现过程出现的错误提前告知我们
interface Emploeey{ | |
name: string | |
salary: number | |
} | |
class Emplmpl implements Emploeey{ //接口的显示实现 | |
name: string | |
salary: number | |
constructor( name:string, salary:number){ //构造函数 | |
this.name = name | |
this.salary = salary | |
} | |
} | |
const emplpml = new Emplmpl('ice_moss', 10000) |
3. 如何选择隐式实现—显示实现
这里我们来举一个例子:我们有一个前端的小程序我们有很多服务,如页面,接口等
定义者 = 实现者
=> 显示实现
在Servce.ts文件中定义接口和实现接口
//Servce.ts | |
//定义接口 | |
interface Servce { | |
login(): void //登录 | |
getTrips(): string //获取行程 | |
getLic(): string //获取驾照号码 | |
startTrip(): void //起始行程 | |
updataLic(lic: string): void //更新驾照号码 | |
} | |
//实现接口 | |
class RPCservce implements Servce { | |
login(): void { | |
throw new Error("Method not implemented."); | |
} | |
getTrips(): string { | |
throw new Error("Method not implemented."); | |
} | |
getLic(): string { | |
throw new Error("Method not implemented."); | |
} | |
startTrip(): void { | |
throw new Error("Method not implemented."); | |
} | |
updataLic(lic: string): void { | |
throw new Error("Method not implemented."); | |
} | |
} |
这里是一个登录页面文件:
//login: Page | |
//file: Login.ts | |
const page ={ | |
servce: new RPCservce() as Servce, | |
onLoginButtonCliked(){ //登录点击按钮 | |
//使用接口 | |
this.servce.login() | |
}} |
可以看出这是显示实现,我们将所的方法都放在接口中使用class RPCservce implements Servce
将接口实现
所以这是:定义者 = 实现者
=> 显示实现
但是我TS中我们更推荐隐式实现:
我们在显示实现中,我们在登录页面只需要调用一个方法:this.servce.login()
来服务
但是我们在调用的时候会.
出很多方法(服务),但我们并不希望看到,使用我们需要使用隐
式实现:使用者 = 实现者
=> 隐式实现
接口的定义由使用者来完成,使用者需要什么方法(服务)再定义需要的接口,我们继续看实例:
//实现接口 | |
class RPCservce{ | |
login(): void { | |
throw new Error("Method not implemented."); | |
} | |
getTrips(): string { | |
throw new Error("Method not implemented."); | |
} | |
getLic(): string { | |
throw new Error("Method not implemented."); | |
} | |
startTrip(): void { | |
throw new Error("Method not implemented."); | |
} | |
updataLic(lic: string): void { | |
throw new Error("Method not implemented."); | |
} | |
} | |
interface Servcelogin { | |
login(): void //登录 | |
} | |
//login: Page 登录页面 | |
//file: Login.ts | |
const loginPage = { | |
loginServce: new RPCservce() as Servcelogin, | |
onLoginButtonCliked(){ | |
//使用接口 | |
this.loginServce.login() | |
}} | |
interface ServceTrips{ | |
getTrips(): string //获取行程 | |
startTrip(): void //起始行程 | |
} | |
//Trips:Page 行程页面 | |
//file: Trips.ts | |
const tripsPage = { | |
tripsServce: new RPCservce() as Servce, | |
tripsButtonCliked(){ | |
this.tripsServce.getTrips() | |
} | |
} |
这样我们就不必使用之前的Servce接口中的方法了,哪一个页面需要使用什么方法(服务),哪一个页面就去定义该接口即可,每一个接口都非常小可能只有一两个函数,这样也便于接口的维护。
四、泛型
1. 介绍
软件工程中,我们不仅要创建一致的定义良好的API,同时也要考虑可重用性。 组件不仅能够支持当前的数据类型,同时也能支持未来的数据类型,这在创建大型系统时为你提供了十分灵活的功能。
在像C#和Java这样的语言中,可以使用泛型
来创建可重用的组件,一个组件可以支持多种类型的数据。 这样用户就可以以自己的需要来选择数据类型来使用组件。
const a: Array<String> = [] | |
a.push('hhhh') | |
console.log(a) | |
const b: Array<number> = [] | |
b.push(100) | |
console.log(b) | |
//输出: | |
["arr", "kk"] | |
["hhhh"] | |
[100] | |
//如果有一万种数据类型,我们是不是需要写一万个这样的函数,显示这不现实,所以我们需要泛型来简化我们的使用: | |
class MyArray<T> { | |
data: T[] = [] | |
add(t: T){ | |
this.data.push(t) | |
} | |
print(){ | |
console.log(this.data) | |
} | |
} | |
const test = new MyArray<string>() | |
test.add('arr') | |
test.add('kk') | |
test.print() | |
//输出: | |
["arr", "kk"] |
下面来再创建第一个使用泛型的例子:identity函数。 这个函数会返回任何传入它的值。 你可以把这个函数当成是 echo
命令。
不用泛型的话,这个函数可能是下面这样:
function identity(arg: number): number { | |
return arg; | |
} |
或者,我们使用any
类型来定义函数:
function identity(arg: any): any { | |
return arg; | |
} |
这样一来,当数据类型不同时,我们需要要写很多功能相同,处理不同类型的函数,使用这里我们需要使用泛型,泛型就像是一种模板,他可以针对任何的数据类型。
使用any
类型会导致这个函数可以接收任何类型的arg
参数,这样就丢失了一些信息:传入的类型与返回的类型应该是相同的。如果我们传入一个数字,我们只知道任何类型的值都有可能被返回。
因此,我们需要一种方法使返回值的类型与传入参数的类型是相同的。 这里,我们使用了 类型变量,它是一种特殊的变量,只用于表示类型而不是值。
function identity<T>(arg: T): T { | |
return arg; | |
} |
我们给identity添加了类型变量T
。 T
帮助我们捕获用户传入的类型(比如:number
),之后我们就可以使用这个类型。 之后我们再次使用了 T
当做返回值类型。现在我们可以知道参数类型与返回值类型是相同的了。 这允许我们跟踪函数里使用的类型的信息。
我们把这个版本的identity
函数叫做泛型,因为它可以适用于多个类型。 不同于使用 any
,它不会丢失信息,像第一个例子那像保持准确性,传入数值类型并返回数值类型。
我们定义了泛型函数后,可以用两种方法使用。 第一种是,传入所有的参数,包含类型参数:
let output = identity<string>("myString"); // type of output will be 'string'
这里我们明确的指定了T
是string
类型,并做为一个参数传给函数,使用了<>
括起来而不是()
。
第二种方法更普遍。利用了类型推论 – 即编译器会根据传入的参数自动地帮助我们确定T的类型:
let output = identity("myString"); // type of output will be 'string'
注意我们没必要使用尖括号(<>
)来明确地传入类型;编译器可以查看myString
的值,然后把T
设置为它的类型。 类型推论帮助我们保持代码精简和高可读性。如果编译器不能够自动地推断出类型的话,只能像上面那样明确的传入T的类型,在一些复杂的情况下,这是可能出现的。
2. 使用泛型变量
使用泛型创建像identity
这样的泛型函数时,编译器要求你在函数体必须正确的使用这个通用的类型。 换句话说,你必须把这些参数当做是任意或所有类型。
看下之前identity
例子:
function identity<T>(arg: T): T { | |
return arg; | |
} |
如果我们想同时打印出arg
的长度。 我们很可能会这样做:
function loggingIdentity<T>(arg: T): T { | |
console.log(arg.length); // Error: T doesn't have .length | |
return arg; | |
} | |
如果这么做,编译器会报错说我们使用了arg
的.length
属性,但是没有地方指明arg
具有这个属性。 记住,这些类型变量代表的是任意类型,所以使用这个函数的人可能传入的是个数字,而数字是没有 .length
属性的。
现在假设我们想操作T
类型的数组而不直接是T
。由于我们操作的是数组,所以.length
属性是应该存在的。 我们可以像创建其它数组一样创建这个数组:
function loggingIdentity<T>(arg: T[]): T[] { | |
console.log(arg.length); // Array has a .length, so no more error | |
return arg; | |
} |
你可以这样理解loggingIdentity
的类型:泛型函数loggingIdentity
,接收类型参数T
和参数arg
,它是个元素类型是T
的数组,并返回元素类型是T
的数组。 如果我们传入数字数组,将返回一个数字数组,因为此时 T
的的类型为number
。 这可以让我们把泛型变量T当做类型的一部分使用,而不是整个类型,增加了灵活性。
我们也可以这样实现上面的例子:
function loggingIdentity<T>(arg: Array<T>): Array<T> { | |
console.log(arg.length); // Array has a .length, so no more error | |
return arg; | |
} |
使用过其它语言的话,你可能对这种语法已经很熟悉了。 在下一节,会介绍如何创建自定义泛型像 Array<T>
一样。
3. 泛型类型
上一节,我们创建了identity通用函数,可以适用于不同的类型。 在这节,我们研究一下函数本身的类型,以及如何创建泛型接口。
泛型函数的类型与非泛型函数的类型没什么不同,只是有一个类型参数在最前面,像函数声明一样:
function identity<T>(arg: T): T { | |
return arg; | |
} | |
let myIdentity: <T>(arg: T) => T = identity; |
我们也可以使用不同的泛型参数名,只要在数量上和使用方式上能对应上就可以。
function identity<T>(arg: T): T { | |
return arg; | |
} | |
let myIdentity: <U>(arg: U) => U = identity; |
我们还可以使用带有调用签名的对象字面量来定义泛型函数:
function identity<T>(arg: T): T { | |
return arg; | |
} | |
let myIdentity: {<T>(arg: T): T} = identity; |
这引导我们去写第一个泛型接口了。 我们把上面例子里的对象字面量拿出来做为一个接口:
interface GenericIdentityFn { | |
<T>(arg: T): T; | |
} | |
function identity<T>(arg: T): T { | |
return arg; | |
} | |
let myIdentity: GenericIdentityFn = identity; |
一个相似的例子,我们可能想把泛型参数当作整个接口的一个参数。 这样我们就能清楚的知道使用的具体是哪个泛型类型(比如: Dictionary<string>而不只是Dictionary
)。 这样接口里的其它成员也能知道这个参数的类型了。
interface GenericIdentityFn<T> { | |
(arg: T): T; | |
} | |
function identity<T>(arg: T): T { | |
return arg; | |
} | |
let myIdentity: GenericIdentityFn<number> = identity; |
注意,我们的示例做了少许改动。 不再描述泛型函数,而是把非泛型函数签名作为泛型类型一部分。 当我们使用 GenericIdentityFn
的时候,还得传入一个类型参数来指定泛型类型(这里是:number
),锁定了之后代码里使用的类型。 对于描述哪部分类型属于泛型部分来说,理解何时把参数放在调用签名里和何时放在接口上是很有帮助的。
除了泛型接口,我们还可以创建泛型类。 注意,无法创建泛型枚举和泛型命名空间。
泛型类看上去与泛型接口差不多。 泛型类使用( <>
)括起泛型类型,跟在类名后面。
class GenericNumber<T> { | |
zeroValue: T; | |
add: (x: T, y: T) => T; | |
} | |
let myGenericNumber = new GenericNumber<number>(); | |
myGenericNumber.zeroValue = 0; | |
myGenericNumber.add = function(x, y) { return x + y; }; |
GenericNumber
类的使用是十分直观的,并且你可能已经注意到了,没有什么去限制它只能使用number
类型。 也可以使用字符串或其它更复杂的类型。
let stringNumeric = new GenericNumber<string>(); | |
stringNumeric.zeroValue = ""; | |
stringNumeric.add = function(x, y) { return x + y; }; | |
console.log(stringNumeric.add(stringNumeric.zeroValue, "test")); |
与接口一样,直接把泛型类型放在类后面,可以帮助我们确认类的所有属性都在使用相同的类型。
我们在类那节说过,类有两部分:静态部分和实例部分。 泛型类指的是实例部分的类型,所以类的静态属性不能使用这个泛型类型。
注:泛型部分参考typescript官方文档