TypeScript 中的接口简介

TypeScript 帮助我们通过允许我们为它们定义细粒式类型检查来保留与 vales 的合同,接口是 TypeScript 实现这一目标的主要机制。

假设我们有以下代码,其中我们定义了两个用户:

 1const user1 = {
 2  id: 1,
 3  firstName: 'John',
 4  lastName: 'Doe',
 5  proUser: false,
 6  email: '[email protected]'
 7}
 8
 9const user2 = {
10  firstName: 'Jane',
11  lastName: 'Doe',
12  proUser: true,
13  email: '[email protected]'
14}

让我们建立一个合约,以便我们的用户对象遵守特定的类型定义:

 1interface User {
 2  id: number;
 3  firstName: string;
 4  lastName: string;
 5  proUser: boolean;
 6  email: string;
 7}
 8
 9const user1: User = {
10  id: 1,
11  firstName: 'John',
12  lastName: 'Doe',
13  proUser: false,
14  email: '[email protected]'
15}
16
17const user2: User = {
18  id: 2,
19  firstName: 'Jane',
20  lastName: 'Doe',
21  proUser: true,
22  email: '[email protected]'
23}

现在,如果我们试图定义缺少属性、附加属性或错误类型的用户对象,TypeScript编译器将投诉并告诉我们我们的用户定义到底是什么错误。

您可以使用 Elvis 操作员(?)在界面中定义可选属性:

 1interface User {
 2  id: number;
 3  firstName: string;
 4  lastName: string;
 5  proUser: boolean;
 6  email: string;
 7  avatar?: string;
 8}
 9
10const user1: User = {
11  id: 1,
12  firstName: 'John',
13  lastName: 'Doe',
14  proUser: false,
15  email: '[email protected]'
16}
17
18const user2: User = {
19  id: 2,
20  firstName: 'Jane',
21  lastName: 'Doe',
22  proUser: true,
23  email: '[email protected]',
24  avatar: 'https://something/my-face.jpg'
25}

请注意,我们不必为 user1 指定任何 avatar 值,TypeScript 不会抱怨。

您的接口可在自己的文件中定义,然后使用 ES6 模块语法导入:

 1import { User } from '../interfaces/user';
 2
 3const user1: User = {
 4  id: 1,
 5  firstName: 'John',
 6  lastName: 'Doe',
 7  proUser: false,
 8  email: '[email protected]'
 9}
10
11// ...
Published At
Categories with 技术
Tagged with
comments powered by Disqus