Young Kbt blog Young Kbt blog
首页
  • java基础

    • Java基础
    • Java集合
    • Java反射
    • JavaJUC
    • JavaJVM
  • Java容器

    • JavaWeb
  • Java版本新特性

    • Java新特性
  • SQL 数据库

    • MySQL
    • Oracle
  • NoSQL 数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • ActiveMQ
    • RabbitMQ
    • RocketMQ
    • Kafka
  • 进阶服务

    • Nginx
  • Spring
  • Spring Boot
  • Spring Security
  • 设计模式
  • 算法
  • 知识
  • 管理

    • Maven
    • Git
  • 部署

    • Linux
    • Docker
    • Jenkins
    • Kubernetes
  • 进阶

    • TypeScript
  • 框架

    • React
    • Vue2
    • Vue3
  • 轮子工具
  • 项目工程
  • 友情链接
  • 本站

    • 分类
    • 标签
    • 归档
  • 我的

    • 收藏
    • 关于
    • Vue2-Admin (opens new window)
    • Vue3-Admin(完善) (opens new window)
GitHub (opens new window)

Shp Liu

朝圣的使徒,正在走向编程的至高殿堂!
首页
  • java基础

    • Java基础
    • Java集合
    • Java反射
    • JavaJUC
    • JavaJVM
  • Java容器

    • JavaWeb
  • Java版本新特性

    • Java新特性
  • SQL 数据库

    • MySQL
    • Oracle
  • NoSQL 数据库

    • Redis
    • ElasticSearch
  • 数据库

    • MyBatis
    • MyBatis-Plus
  • 消息中间件

    • ActiveMQ
    • RabbitMQ
    • RocketMQ
    • Kafka
  • 进阶服务

    • Nginx
  • Spring
  • Spring Boot
  • Spring Security
  • 设计模式
  • 算法
  • 知识
  • 管理

    • Maven
    • Git
  • 部署

    • Linux
    • Docker
    • Jenkins
    • Kubernetes
  • 进阶

    • TypeScript
  • 框架

    • React
    • Vue2
    • Vue3
  • 轮子工具
  • 项目工程
  • 友情链接
  • 本站

    • 分类
    • 标签
    • 归档
  • 我的

    • 收藏
    • 关于
    • Vue2-Admin (opens new window)
    • Vue3-Admin(完善) (opens new window)
GitHub (opens new window)
  • 超文本标记语言 - Html

  • 解释编程语言 - JavaScript

  • JS 超集语言 - TypeScript

    • TypeScript - 介绍
    • TypeScript - 安装和使用
    • TypeScript - 基本类型
    • TypeScript - 编译和配置
    • TypeScript - 文件打包
    • TypeScript - 接口
      • 接口(Interface)
      • 接口初探
      • 可选属性
      • 只读属性
        • readonly vs const
      • 额外的属性检查
      • 函数类型
      • 可索引的类型
      • 类的类型
        • 实现接口
        • 类静态部分与实例部分的区别
      • 继承接口
      • 混合类型
      • 接口继承类
    • TypeScript - 函数
    • TypeScript - 类
    • TypeScript - 泛型
    • TypeScript - 类型推断
    • TypeScript - 高级类型
    • TypeScript Office - 入门
    • TypeScript Office - 常用类型
    • TypeScript Office - 类型缩小
    • TypeScript Office - 更多函数
    • TypeScript Office - 对象类型
    • TypeScript Office - 类型操纵
    • TypeScript Office - 类
    • TypeScript Office - 模块
    • TypeScript Office - 变量声明
    • TypeScript Office - 类型推断
    • TypeScript Office - 枚举
    • TypeScript Office - 公共类型
    • TypeScript Office - Symbols
    • TypeScript Office - 类型兼容性
    • TypeScript Office - 迭代器和生成器
    • TypeScript Office - 装饰器
    • TypeScript Office - JSX
    • TypeScript Office - 混入
    • TypeScript Office - 三斜线指令
    • TypeScript Office - 模块进阶
    • TypeScript Office - 模块解析
    • TypeScript Office - 命名空间
    • TypeScript Office - 命名空间与模块
    • TypeScript Office - 声明合并
  • 界面构建框架 - React

  • 渐进式框架 - Vue2

  • 渐进式框架 - Vue3

  • 前端
  • JS 超集语言 - TypeScript
Young Kbt
2022-09-08
目录

TypeScript - 接口

  • 接口(Interface)
  • 接口初探
  • 可选属性
  • 只读属性
    • readonly vs const
  • 额外的属性检查
  • 函数类型
  • 可索引的类型
  • 类的类型
    • 实现接口
    • 类静态部分与实例部分的区别
  • 继承接口
  • 混合类型
  • 接口继承类

# 接口(Interface)

TypeScript 的核心原则之一是对值所具有的结构进行类型检查。它有时被称做「鸭式辨型法」或「结构性子类型化」。在 TypeScript 里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

接口的作用类似于抽象类,不同点在于:接口中的所有方法和属性都是没有实值的,换句话说接口中的所有方法都是抽象方法;

接口主要负责定义一个类的结构,接口可以去限制一个对象的接口:对象只有包含接口中定义的所有属性和方法时才能匹配接口;

同时,可以让一个类去实现接口,实现接口时类中要保护接口中的所有属性。

如下例子:

interface Demo {
    name: string;
    age: number;
    checked: boolean;
}
1
2
3
4
5

此时这个叫做 Demo 的接口有三个属性,并且指定了对应的类型,那么我们引用 Demo 时,就必须给这三个属性赋上对应类型的值,如下:

let demo: Demo {
    name: "kele";
    age: 18;
    checked: true;
}
1
2
3
4
5

如果属性的值不符合接口的规定,如 checked 不为 true 或者 false,则编译器会报错。

规范:接口名开头大写,属性直接可以空格、逗号、分号隔开,如上面的例子是分号隔开。

# 接口初探

下面通过一个简单示例来观察接口是如何工作的:

function printLabel(labelledObj: { label: string }) {
    console.log(labelledObj.label);
}

let myObj = { size: 10, label: 'Size 10 Object' };
printLabel(myObj);
1
2
3
4
5
6

类型检查器会查看 printLabel 的调用。printLabel 有一个参数,并要求这个对象参数有一个名为 label 类型为 string 的属性。需要注意的是,我们传入的对象参数实际上会包含很多属性,但是编译器只会检查那些必需的属性是否存在,以及其类型是否匹配。然而,有些时候 TypeScript 却并不会这么宽松,我们下面会稍做讲解。

下面我们重写上面的例子,这次使用接口来描述:必须包含一个 label 属性且类型为 string:

interface LabelledValue {
    label: string;
}

function printLabel(labelledObj: LabelledValue) {
    console.log(labelledObj.label);
}

let myObj = {size: 10, label: 'Size 10 Object'};
printLabel(myObj);
1
2
3
4
5
6
7
8
9
10

LabelledValue 接口就好比一个名字,用来描述上面例子里的结构。它代表了有一个 label 属性且类型为 string 的对象。需要注意的是,我们在这里并不能像在其它语言里一样,说传给 printLabel 的对象实现了这个接口。我们只会去关注值的外形。只要传入的对象满足上面提到的必要条件,那么它就是被允许的。

还有一点值得提的是,类型检查器不会去检查属性的顺序,只要相应的属性存在并且类型也是对的就可以。

# 可选属性

接口里的属性不全都是必需的。有些是只在某些条件下存在,或者根本不存在。例如给函数传入的参数对象中只有部分属性赋值了。

interface Square {
    color: string;
    area: number;
}

interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare (config: SquareConfig): Square {
    let newSquare = {color: 'white', area: 100};
    if (config.color) {
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({color: 'black'})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个 ? 符号。

可选属性的好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误。比如,我们故意将 createSquare 里的 color 属性名拼错,就会得到一个错误提示:

interface Square {
    color: string,
    area: number
}

interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare(config: SquareConfig): Square {
    let newSquare = {color: 'white', area: 100};
    if (config.clor) {
        // Error: 属性 'clor' 不存在于类型 'SquareConfig' 中
        newSquare.color = config.clor;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({color: 'black'});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

当一个对象的属性是可以出现,又不可以出现时(不是必须的属性),就需要用到可选属性 ? 修饰.

可能还对可选属性的场景不理解:没有 ? 修饰的属性,要求必须进行属性初始化,在我很多场景下,我们往往认为一些属性不是必须的,它在某些地方会用到,在某些地方却用不到,这种不是必须的属性就用 ? 修饰。

# 只读属性

一些对象属性只能在对象刚刚创建的时候修改其值。你可以在属性名前用 readonly 来指定只读属性:

interface Point {
    readonly x: number;
    readonly y: number;
}
1
2
3
4

你可以通过赋值一个对象字面量来构造一个 Point。赋值后,x 和 y 再也不能被改变了。

let p1: Point = {
    x: 10;
    y: 20;
};
p1.x = 5; // error
1
2
3
4
5

TypeScript 具有 ReadonlyArray<T> 类型,它与 Array<T> 相似,只是把所有可变方法去掉了,因此可以确保数组创建后再也不能被修改:

let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error
ro.push(5); // error
ro.length = 100; // error
a = ro; // error
1
2
3
4
5
6

上面代码的最后一行,可以看到就算把整个 ReadonlyArray 赋值到一个普通数组也是不可以的。但是你可以用类型断言重写:

a = ro as number[];
1

这样 a 就能赋值了。

# readonly vs const

最简单判断该用 readonly 还是 const 的方法是看要把它做为变量使用还是做为一个属性。做为变量使用的话用 const,若做为属性则使用 readonly。

# 额外的属性检查

我们在第一个例子里使用了接口,TypeScript 让我们传入 { size: number; label: string; } 到仅期望得到 { label: string; } 的函数里,并且我们已经学过了可选属性,即 {size?: number; label: string; },这样可以让 size 属性无须初始化。

然而,天真地将这两者结合的话就会像在 JavaScript 里那样搬起石头砸自己的脚。比如,拿 createSquare 例子来说:

interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare (config: SquareConfig): { color: string; area: number } {
    let newSquare = {
        color: 'white';
        area: 100;
    }
    if (config.color) {
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({ colour: 'red', width: 100 });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

注意传入 createSquare 的参数拼写为 colour 而不是 color。在 JavaScript 里,这会默默地失败。

你可能会争辩这个程序已经正确地类型化了,因为 width 属性是兼容的,不存在 color 属性,而且额外的 colour 属性是无意义的。

然而,TypeScript 会认为这段代码可能存在 bug。对象字面量会被特殊对待而且会经过额外属性检查,当将它们赋值给变量或作为参数传递的时候。如果一个对象字面量存在任何「目标类型」不包含的属性时,你会得到一个错误。

// error: 'colour' 不存在于类型 'SquareConfig' 中
let mySquare = createSquare({ colour: 'red', width: 100 });
1
2

而我们明明让 color 是可选属性,但还是无法逃开编辑器,因为 colour 和 color 无法匹配。

绕开这些检查非常简单。最简便的方法是使用类型断言:

let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
1

然而,这种类型断言仅仅是欺骗编辑器来达到想要的效果,而最佳的方式是能够添加一个字符串索引签名,前提是你能够确定这个对象可能具有某些做为特殊用途使用的额外属性。如果 SquareConfig 带有上面定义的类型的 color 和 width 属性,并且还会带有任意数量的其它属性,那么我们可以这样定义它:

interface SquareConfig {
    color?: string;
    width?: number;
    [propName: string]: any;
}
1
2
3
4
5

我们稍后会讲到索引签名(propName 代表属性,string 代表属性的类型,any 代表属性值的类型),但在这我们要表示的是 SquareConfig 可以有任意数量的属性,并且只要它们不是 color 和 width,那么就无所谓它们的类型是什么。

还有最后一种跳过这些检查的方式,这可能会让你感到惊讶,它就是将这个对象赋值给一个另一个变量:因为 squareOptions 不会经过额外属性检查,所以编译器不会报错。

let squareOptions = { colour: 'red', width: 100 };
let mySquare = createSquare(squareOptions);
1
2

要留意,在像上面一样的简单代码里,你可能 不应该去绕开这些检查。对于包含方法和内部状态的复杂对象字面量来讲,你可能需要使用这些技巧,但是大多数额外属性检查错误是真正的 bug。也就是说你遇到了额外类型检查出的错误,你应该去审查一下你的类型声明。

在这里,如果支持传入 color 或 colour 属性到 createSquare,你应该修改 SquareConfig 定义来体现出这一点。

# 函数类型

接口能够描述 JavaScript 中对象拥有的各种各样的外形。除了描述带有属性的普通对象外,接口也可以描述函数类型。

为了使用接口表示函数类型,我们需要给接口定义一个调用签名。它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。

interface SearchFunc {
    (source: string, subString: string): boolean;
}
1
2
3

这样定义后,我们可以像使用其它接口一样使用这个函数类型的接口。下例展示了如何创建一个函数类型的变量,并将一个同类型的函数赋值给这个变量。

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string): boolean {
    let result = source.search(subString);
    return result > -1;
}
1
2
3
4
5

对于函数类型的类型检查来说,函数的参数名不需要与接口里定义的名字相匹配。比如,我们使用下面的代码重写上面的例子:

let mySearch: SearchFunc;
mySearch = function(src: string, sub: string): boolean {
    let result = src.search(sub);
    return result > -1;
}
1
2
3
4
5

函数的参数会逐个进行检查,要求对应位置上的参数类型是兼容的。如果你不想指定类型,TypeScript 的类型系统会推断出参数类型,因为函数直接赋值给了 SearchFunc 类型变量。函数的返回值类型是通过其返回值推断出来的(此例是 false 和 true)。如果让这个函数返回数字或字符串,类型检查器会警告我们函数的返回值类型与 SearchFunc 接口中的定义不匹配。

let mySearch: SearchFunc;
mySearch = function(src, sub) {
    let result = src.search(sub);
    return result > -1;
}
1
2
3
4
5

# 可索引的类型

与使用接口描述函数类型差不多,我们也可以描述那些能够「通过索引得到」的类型,比如 a[10] 或 ageMap['daniel']。可索引类型具有一个索引签名,它描述了对象索引的类型,还有相应的索引返回值类型。让我们看一个例子:

interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ['Bob', 'Fred'];

let myStr: string = myArray[0];
1
2
3
4
5
6
7
8

上面例子里,我们定义了 StringArray 接口,它具有索引签名。这个索引签名表示了当用 number 去索引 StringArray 时会得到 string 类型的返回值。

TypeScript 支持两种索引签名:字符串和数字。可以同时使用两种类型的索引,但是数字索引的返回值必须是字符串索引返回值类型的子类型。这是因为当使用 number 来索引时,JavaScript 会将它转换成 string 然后再去索引对象。也就是说用 100(一个 number)去索引等同于使用'100'(一个 string )去索引,因此两者需要保持一致。

class Animal {
    name: string;
}
class Dog extends Animal {
    breed: string;
}

// 错误:使用数值型的字符串索引,有时会得到完全不同的 Animal
interface NotOkay {
    [x: number]: Animal;
    [x: string]: Dog;
}
1
2
3
4
5
6
7
8
9
10
11
12

字符串索引签名能够很好的描述 dictionary 模式,并且它们也会确保所有属性与其返回值类型相匹配。因为字符串索引声明了 obj.property 和 obj['property'] 两种形式都可以。下面的例子里,name 的类型与字符串索引类型不匹配,所以类型检查器给出一个错误提示:

interface NumberDictionary {
    [index: string]: number;
    length: number;    // 可以,length 是 number 类型
    name: string;      // 错误,name 的类型与索引类型返回值的类型不匹配
}
1
2
3
4
5

最后,你可以将索引签名设置为只读,这样就防止了给索引赋值:

interface ReadonlyStringArray {
    readonly [index: number]: string;
}
let myArray: ReadonlyStringArray = ['Alice', 'Bob'];
myArray[2] = 'Mallory'; // error
1
2
3
4
5

# 类的类型

# 实现接口

与 C# 或 Java 里接口的基本作用一样,TypeScript 也能够用它来明确的强制一个类去符合某种契约。

interface ClockInterface {
    currentTime: Date;
}

class Clock implements ClockInterface {
    currentTime: Date;
    constructor(h: number, m: number) { }
}
1
2
3
4
5
6
7
8

你也可以在接口中描述一个方法,在类里实现它,如同下面的 setTime 方法一样:

interface ClockInterface {
    currentTime: Date;
    setTime(d: Date)
}

class Clock implements ClockInterface {
    currentTime: Date;
    setTime(d: Date) {
        this.currentTime = d;
    }
    constructor(h: number, m: number) { }
}
1
2
3
4
5
6
7
8
9
10
11
12

接口描述了类的公共部分,而不是公共和私有两部分。它不会帮你检查类是否具有某些私有成员。

# 类静态部分与实例部分的区别

当你操作类和接口的时候,你要知道类是具有两个类型的:静态部分的类型和实例的类型。你会注意到,当你用构造器签名去定义一个接口并试图定义一个类去实现这个接口时会得到一个错误:

interface ClockConstructor {
    new (hour: number, minute: number);
}

// error
class Clock implements ClockConstructor {
    currentTime: Date;
    constructor(h: number, m: number) { }
}
1
2
3
4
5
6
7
8
9

这里因为当一个类实现了一个接口时,只对其实例部分进行类型检查。constructor 存在于类的静态部分,所以不在检查的范围内。

看下面的例子,我们定义了两个接口,ClockConstructor 为构造函数所用和 ClockInterface 为实例方法所用。为了方便我们定义一个构造函数 createClock,它用传入的类型创建实例。

interface ClockConstructor {
    new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
    tick();
}

function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
    return new ctor(hour, minute);
}

class DigitalClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log('beep beep');
    }
}
class AnalogClock implements ClockInterface {
    constructor(h: number, m: number) { }
    tick() {
        console.log('tick tock');
    }
}

let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

因为 createClock 的第一个参数是 ClockConstructor 类型,在 createClock(AnalogClock, 7, 32) 里,会检查 AnalogClock 是否符合构造函数签名。

# 继承接口

和类一样,接口也可以相互继承。这让我们能够从一个接口里复制成员到另一个接口里,可以更灵活地将接口分割到可重用的模块里。

interface Shape {
    color: string;
}

interface Square extends Shape {
    sideLength: number;
}

let square = {} as Square;
square.color = 'blue';
square.sideLength = 10;
1
2
3
4
5
6
7
8
9
10
11

一个接口可以继承多个接口,创建出多个接口的合成接口。

interface Shape {
    color: string;
}

interface PenStroke {
    penWidth: number;
}

interface Square extends Shape, PenStroke {
    sideLength: number;
}

let square = {} as Square;
square.color = 'blue';
square.sideLength = 10;
square.penWidth = 5.0;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 混合类型

先前我们提过,接口能够描述 JavaScript 里丰富的类型。因为 JavaScript 其动态灵活的特点,有时你会希望一个对象可以同时具有上面提到的多种类型。

一个例子就是,一个对象可以同时做为函数和对象使用,并带有额外的属性。

interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

function getCounter(): Counter {
    let counter = (function (start: number) { }) as Counter;
    counter.interval = 123;
    counter.reset = function () { };
    return counter;
}

let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

在使用 JavaScript 第三方库的时候,你可能需要像上面那样去完整地定义类型。

# 接口继承类

当接口继承了一个类的类型时,它会继承类的成员但不包括其实现。就好像接口声明了所有类中存在的成员,但并没有提供具体实现一样。接口同样会继承到类的 private 和 protected 成员。这意味着当你创建了一个接口继承了一个拥有私有或受保护的成员的类时,这个接口类型只能被这个类或其子类所实现(implement)。

当你有一个庞大的继承结构时这很有用,但要指出的是你的代码只在子类拥有特定属性时起作用。这个子类除了继承至基类外与基类没有任何关系。

例:

class Control {
    private state: any;
}

interface SelectableControl extends Control {
    select(): void
}

class Button extends Control implements SelectableControl {
    select() { }
}

class TextBox extends Control {
    select() { }
}

// Error:ImageC 类型缺少 state 属性
class ImageC implements SelectableControl {
    select() { }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

在上面的例子里,SelectableControl 包含了 Control 的所有成员,包括私有成员 state。因为 state 是私有成员,所以只能够是 Control 的子类们才能实现 SelectableControl 接口。因为只有 Control 的子类才能够拥有一个声明于 Control 的私有成员 state,这对私有成员的兼容性是必需的。

在 Control 类内部,是允许通过 SelectableControl 的实例来访问私有成员 state 的。实际上,SelectableControl 接口和拥有 select 方法的 Control 类是一样的。Button和 TextBox 类是 SelectableControl 的子类(因为它们都继承自 Control 并有 select 方法),但 ImageC 类并不是这样的。

编辑此页 (opens new window)
#TypeScript
更新时间: 2023/09/18, 16:34:13
TypeScript - 文件打包
TypeScript - 函数

← TypeScript - 文件打包 TypeScript - 函数→

最近更新
01
技术随笔 - Element Plus 修改包名 原创
11-02
02
Reactor - 扩展性
11-02
03
Reactor - 最佳实践
11-02
更多文章>
Theme by Vdoing | Copyright © 2021-2024 Young Kbt | blog
桂ICP备2021009994号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式