1. 数组类型
javascript
const list1: number[] = [1, 2, 3];
const list2: Array<number> = [1, 2, 3];
const list3: [number, string, boolean] = [1, '2', true];
const list4: [{ name: string; age: number }] = [{ name: 'Jack', age: 30 }];
const list5: Array<{ name: string; age: number }> = [{ name: 'Jack', age: 30 }];
interface User {
name: string
age: number
}
const list6: Array<User> = [{ name: 'jack', age: 30 }]
2. 函数类型
javascript
function add1(a: number, b: number): number {
return a + b
}
function add2(a: number, b: number): void {
console.log(a, b)
}
function add3(a: number, b: number): unknown {
throw new Error('Error')
}
const add4 = (a: number, b: number): number => {
return a + b
}
const add5: (a: number, b: number) => number = (a, b) => {
return a + b
}
3. 元组类型
javascript
const list: [number, string, boolean, object] = [1, '2', true, {}]
4. 交叉类型
javascript
type AgeType = { age: number }
type UserType = { id: number; name: string }
const user: UserType & AgeType = { id: 1, name: 'Jack', age: 30 }
const userAge: AgeType = { age: 30 }
const userInfo: UserType = { id: 2, name: 'Tom' }
5. 接口类型
5.1. 类型的定义
javascript
interface Person {
name: string
age: number
}
const Jack: Person = {
name: 'Jack',
age: 30
}
const Tom: Person = {
name: 'Tom',
age: 30
}
5.2. 定义只读可选
javascript
interface Student {
readonly name: string
age?: number
}
const Lily:Student = {
name: 'Lily'
// 由于age为可选属性,只处可以省略
}
Lily.name = 'Tom'
// 报错,因为是只读属性
5.3. 定义任意属性
javascript
interface Student {
age: number,
name: string,
// 任意属性类型一定要为已声明属性的父类型,一般用联合类型,也可以用任意类型。
[k: string]: string | number
}
const Jack:Student = {
id: 1,
age: 30,
edu: '本科'
name: 'Jack',
gender: 'male',
}
任意属性类型一定要为已声明属性的父类型,一般用联合类型,也可以用任意类型。
5.4. 接口定义函数
javascript
interface Sum {
(x: number, y: number): number
}
const add: Sum = (x, y) => {
return x + y
}
也可以通过type定义函数类型。
javascript
type Sum = (x: number, y: number) => number
5.5. 接口的继承
javascript
interface User {
id: number
name: string
}
interface Person extends User{
age: number
}
interface Person {
gender: string
}
const Tim: Person = {
id: 1,
age: 30,
name: 'Tim',
gender: 'Male'
}
通过type来实现类似于接口的继承。
javascript
type User = { id: number; name: string }
type Person = { age: number } | User
const Tim: Person = {
id: 1,
age: 30,
name: 'Tim',
}
6. 接口和Type区别?
-
接口通过interface定义,type是用来定义类型别名;
-
接口可以重复定义,type不可以;
-
接口可以继承,type不可以继承,但是可以使用联合类型和交叉类型来模拟继承;