接口

1
2
3
4
5
6
7
8
9
interface InfoType {
name: string
age: number
}

const info: InfoType = {
name: '常威',
age: 18
}

索引类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
interface IndexLanguage {
[index: number]: string
}

const frontLanguage: IndexLanguage = {
0: 'html',
1: 'css',
2: 'JavaScript',
2: 'Vue'
}

interface LanguageYear {
[name: string]: number
}

const languageYear: LanguageYear = {
'C': 1972,
'Java': 1995,
'JavaScript': 1996,
'typescript': 2014
}

函数类型

1
2
3
4
5
6
7
8
9
10
11
12
13
interface CalcFn {
(n1: number, n2: number): number
}

function calc(num1: number, num2: number, calcFn: CalcFn) {
return calcFn(num1, num2)
}

const add: CalcFn = (num1, num2) => {
return num1 + num2
}

calc(20, 30, add)

接口的继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface ISwim {
swimming: () => void
}

interface IFly {
flying: () => void
}

interface IAction extends ISwim, IFly {}

const action: IAction = {
swimming() {},
flying() {}
}

交叉类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
interface ISwim {
swimming: () => void
}

interface IFly {
flying: () => void
}

type MyType1 = ISwim | IFly
type MyType2 = ISwim & IFly

const obj1: MyType1 = {
flying() {}
}

const obj2: MyType2 = {
swimming() {},
flying() {}
}