# 接口

WARNING

  • 基本用法
  • 可选属性
  • 多余属性检查
  • 绕开多余属性检查
  • 只读属性
  • 函数类型
  • 索引类型
  • 继承接口
  • 混合类型接口
  • 基础用法
let getFullNamee = ({ firstName, lastName }: any) => {
	return `${firstName} ${lastName}`
}

getFullNamee({
	firstName: 'jiang',
	lastName: 18 // 期望是字符串而不能是数字
})


1
2
3
4
5
6
7
8
9
10

使用接口规范函数传参

interface NameInfo {
	firstName: string,
	lastName: string
}

let getFullNamee = ({ firstName, lastName }: NameInfo) => {
	return `${firstName} ${lastName}`
}

getFullNamee({
	firstName: 'jiang',
	lastName: 'xiaoyu'
})
1
2
3
4
5
6
7
8
9
10
11
12
13

函数传参可选,非必传情况

interface Vegetable {
	color?: string, // ? 表示可选
	type: string
}

let getVegetables = ({ color, type }: Vegetable) => {
	return `A ${color ? color : '没值'}-${type}`
}

getVegetables({
	type: '方形'
})
1
2
3
4
5
6
7
8
9
10
11
12

绕开多余属性检查

  • 类型断言
  • 接口
  • 类型兼容性

interface Vegetable {
	color?: string, // ? 表示可选
	type: string
}

let getVegetables = ({ color, type }: Vegetable) => {
	return `A ${color ? color : '没值'}-${type}`
}
// 使用断言方式 as
getVegetables({
	type: '方形',
	size: 20 // 多传一个属性
} as Vegetable)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

在接口中定义多余属性

interface Vegetable {
	color?: string, // ? 表示可选
	type: string,
	[prop: string]: any // 多余属性
}

let getVegetables = ({ color, type }: Vegetable) => {
	return `A ${color ? color : '没值'}-${type}`
}

getVegetables({
	type: '方形',
	size: 20 // 多传一个属性
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14

类型兼容性,只要对象 objData 里包含着必须的属性即可。


interface Vegetable {
	color?: string, // ? 表示可选
	type: string
}

let getVegetables = ({ color, type }: Vegetable) => {
	return `A ${color ? color : '没值'}-${type}`
}

let objData = {
	color: '红色',
	type: '方形',
	size: 20 // 多传一个属性
}
getVegetables(objData)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

只读属性

interface Vegetable {
	color?: string, // ? 表示可选
	readonly type: string, // 只读属性设置
	[prop: string]: any // 多余属性
}
1
2
3
4
5
interface ArrInter {
	0: number,
	readonly 1: string
}

let arr: ArrInter = [1, '你好']
// arr[1] = '哈哈' // 只读属性不允许修改
1
2
3
4
5
6
7

定义函数接口

interface AddFunc {
	(num1: number, num2: number): number
}

let addFunc: AddFunc = (n1, n2) => n1 + n2

1
2
3
4
5
6

给索引指定类型


interface RoleDic {
	[id: number]: string
}
let role1: RoleDic = {
	1: '索引必须是数字'
}

1
2
3
4
5
6
7
8

接口的继承


interface Vegetables {
	color: string
}

interface Tomato extends Vegetables{
	radius: number
}

interface Carrot extends Vegetables{
	length: number
}

1
2
3
4
5
6
7
8
9
10
11
12
13

混合类型

// 混合类型接口
// 提示报错了
interface Counter {
	(): void,
	count: number
}
let getCounter = (): Counter => {
	let c = () => { c.count++ }
	c.count = 0
	return c
}
let counter: Counter = getCounter()
counter()
console.log(counter.count)
1
2
3
4
5
6
7
8
9
10
11
12
13
14