TypeScript接口(interface)定义 -interface

TypeScript接口(interface)定义 -interface

_

在 TypeScript 项目中,经常会看到类似下面的写法:

export interface LineElementData {
  id: string;
  startX: number;
  startY: number;
  endX: number;
}

这是一种 TypeScript 接口(interface)定义,用于描述对象的数据结构。


一、TypeScript 简介

TypeScript 是 JavaScript 的超集,在 JS 的基础上增加了:

  • 静态类型检查

  • 接口(interface)

  • 类型推导

  • 更好的 IDE 支持

TypeScript 代码最终会被编译成普通的 JavaScript 代码运行。


二、interface 的作用

interface 用于定义对象的形状(Shape),即:

  • 对象必须有哪些属性

  • 每个属性的类型是什么

它只在开发阶段生效,用于类型校验,不会影响运行时。


三、示例代码解析

export interface LineElementData {
  id: string;
  startX: number;
  startY: number;
  endX: number;
}

逐项说明:

1. export

表示该接口可以被其他文件导入使用,符合 ES Module 规范。

2. interface

TypeScript 关键字,用于声明接口。

3. LineElementData

接口名称,一般使用 PascalCase(大驼峰命名),语义为“线条元素的数据结构”。

4. 接口体

定义了对象必须包含的属性:

  • id: string:唯一标识

  • startX: number:起点 X 坐标

  • startY: number:起点 Y 坐标

  • endX: number:终点 X 坐标


四、interface 的常见用法

1. 作为变量类型

const lineData: LineElementData = {
  id: "line-001",
  startX: 100,
  startY: 200,
  endX: 300
};
  • 缺少属性或类型错误,编译阶段就会报错

  • 多写、少写属性都会被校验


2. 作为函数参数类型

function drawLine(line: LineElementData) {
  console.log(line.startX, line.startY, line.endX);
}

调用函数时,TypeScript 会自动检查参数结构是否正确。


3. 作为函数返回值类型

function createLine(id: string): LineElementData {
  return {
    id,
    startX: 0,
    startY: 0,
    endX: 100
  };
}

返回值必须完全符合接口定义。


五、interface 的进阶特性

1. 可选属性(Optional)

export interface LineElementData {
  id: string;
  startX: number;
  startY: number;
  endX: number;
  endY?: number;
  color?: string;
}

? 表示该属性可以存在,也可以不存在


2. 只读属性(Readonly)

export interface LineElementData {
  readonly id: string;
  startX: number;
  startY: number;
  endX: number;
}
  • id 初始化后不能被修改

  • 常用于唯一标识、业务主键等场景


3. 接口继承(extends)

interface BaseElement {
  id: string;
  type: string;
}

export interface LineElementData extends BaseElement {
  startX: number;
  startY: number;
  endX: number;
  endY: number;
}

适合在复杂项目中复用公共字段。


六、为什么要用 interface?

1. 提高类型安全

function calculateLength(line: LineElementData): number {
  return line.endX - line.startX;
}

避免因属性不存在或类型错误导致的运行时问题。


2. 更好的 IDE 体验

  • 自动补全

  • 参数提示

  • 重构更安全


3. 提升代码可读性和维护性

function renderLine(
  line: LineElementData,
  ctx: CanvasRenderingContext2D
): void {}

函数一眼就能看出需要什么数据。


七、TypeScript vs JavaScript 对比

特性

JavaScript

TypeScript

类型系统

动态

静态

错误发现

运行时

编译时

接口 / 类型

interface / type

大型项目

维护困难

易维护


八、实际项目中的使用场景

// types.ts
export interface User {
  id: string;
  name: string;
  email: string;
  age?: number;
}
// 组件中
const UserProfile: React.FC<{ user: User }> = ({ user }) => {
  return <div>{user.name}</div>;
};

TypeScript 中的接口继承(extends) 2026-01-26
前端 AES 加密 2026-01-26

评论区