0%

Typescript-Interface

  • 在TypeScript中,我们使用接口(Interfaces)来定义对象的类型。除了可用于对类的一部分行为进行抽象以外,也常用于对「对象的形状(Shape)」进行描述
  • TypeScript 的核心原则之一是对值所具有的结构进行类型检查, 在 TypeScript 里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约
  • interface 这个概念在js中并没有,所以 interface 编译后并不会呈现到 js 中,只会进行静态的类型检查
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
interface NameInfo {
firstName: string,
lastName: string
}

// const getFullName = ({ firstName, lastName }: { firstName: string, lastName: string }): string => {
const getFullName = ({ firstName, lastName }: NameInfo): string => {
return `firstName: ${firstName}, lastName: ${lastName}`
}

const obj = {
firstName: 'tan',
lastName: 'ln'
}
getFullName(obj)
  1. 可选属性

    1
    2
    3
    4
    5
    interface Person {
    name: string,
    age: number,
    car?: string // 可选
    }
  2. 索引签名 任意属性

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    interface NameInfo {
    firstName: string,
    lastName: string,
    [prop: string]: any // 索引签名 多余属性检测
    }
    getFullName({
    firstName: 'tan',
    lastName: 'ln',
    age: 0
    })
  3. 只读属性

    1
    2
    3
    4
    interface Person {
    car?: string, // 可选
    readonly type: string // 只读
    }

数组接口

1
2
3
4
5
6
interface ArrInterface {
0: number,
readonly 1: string
}
let arr: ArrInterface = [0, '0']
arr[1] = '' // error

函数接口

1
2
3
4
5
6
7
8
interface addFun {
(n1: number, n2: number): number
}
// ts 建议使用 type 类型别名
// type addFun = (n1: number, n2: number) => number

const add: addFun = (n1, n2) => n1 + n2
add(10, 0)

可索引类型接口

1
2
3
4
5
6
interface IdInterface {
[id: number]: string
}
const r1: IdInterface = {
0: 'id_000'
}

TypeScript 支持两种索引签名:字符串和数字 可以同时使用两种类型的索引

接口继承

1
2
3
4
5
6
7
8
9
10
interface Person {
age: number
}
interface A extends Person {
car: string
}
const a: A = {
age: 100,
car: 'AMG'
}
-------------本文结束感谢您的阅读-------------