interface
更多详细介绍请看阮老师的文章 TypeScript 的 interface 接口 - TypeScript 教程 - 网道 (wangdoc.com)
对象的模板
1. 基本用法
interface Person {
firstName: string
lastName: string
age: number
}
const p: Person = {
firstName: 'vino',
lastName: 'wang',
age: 18
}
// 方括号运算符可以取出某个属性的类型
type Age = Person['age'] // number
2. 表示对象的形式
- 对象属性
interface Point {
x: number
y: number
a?: string
readonly b:number
}
- 对象索引
interface A {
[prop: string]: number
}
interface B {
[prop: number]: string
}
interface C{
[prop: string]: number
[prop: number]: string // 报错
}
- 对象方法
interface C {
f(x: string): string
}
interface CC {
f: (x: string)=> string
}
- 函数
interface F {
(x: number, y: number): number
}
const f: F = (x, y) => x + y
const ff: F = (x, y) => x - y
- 构造函数
interface G {
new(msg: string): Error
}
3. interface 的继承
- interface extends interface
interface A {
a: string
}
interface C {
c: number
}
interface B extends A, C {
b: number
}
interface D extends A {
a: '1' // 必须兼容于A.a的类型
}
- interface extends type
type 必须是一个对象,才能被继承
type A = {
a: string
}
interface B extends A {
b: number
}
- interface extends Class
class A {
a: string
}
interface b extends A {
c: number
}
4. 多个同名接口会合并成一个接口
这样的设计主要是为了兼容 JavaScript 的行为。JavaScript 开发者常常对全局对象或者外部库,添加自己的属性和方法。那么,只要使用 interface 给出这些自定义属性和方法的类型,就能自动跟原始的 interface 合并,使得扩展外部类型非常方便。
interface A {
a: string
}
interface A {
b: number
}
interface Document {
foo: string
}
document.foo ='foo'
5. interface 与 type 的异同
相同点:
- 都可以表示对象类型
不同点:
-
type 能表示非对象类型,interface 只能表示对象类型
-
interface 可以继承其他类型,type 不支持继承。或者说两者的继承方式不同
继承的主要作用是为了添加属性,type 添加属性的方式是使用
&符号
-
同名的 interface 会自动合并,同名 type 则会报错
-
interface 不能包含映射属性,type 可以
type A ={
[Key in keyof P] : P[key]
}
// 报错
interface B {
[Key in keyof P] : P[key]
}
- this 关键字只能用于 interface
interface Foo {
add( num: number ): this
}
- type 可以扩展原始数据类型,interface 不行
type MyStr = string & {
type: 'new'
};
- type 可以表达更为复杂的类型 jing