TypeScript 面试题:type 与 interface 的区别与相同点

相同点 ✅

两者都可以定义对象结构:

typescript 复制代码
// interface 定义对象
interface User {
  name: string;
  age: number;
  avatarUrl: string;
}

// type 定义对象(相同)
type UserType = {
  name: string;
  age: number;
  avatarUrl: string;
}

const u1: User = {
  name: 'yihao',
  age: 18,
  avatarUrl: 'https://yihao.com',
}

const u2: UserType = {
  name: 'zhangsan',
  age: 20,
  avatarUrl: 'https://zhangsan.com',
}

两者都支持继承:

typescript 复制代码
// interface 用 extends 继承
interface Person {
  name: string;
}
interface Employee extends Person {
  job: string;
}

// type 用交叉类型 & 继承
type PersonType = {
  name: string;
}
type EmployeeType = PersonType & {
  job: string;
}

const e1: EmployeeType = {
  name: 'yihao',
  job: '字节跳动Agent开发工程师',
}

两者都可以定义函数类型:

typescript 复制代码
// interface 定义函数
interface AddFn {
  (a: number, b: number): number;
}
const add1: AddFn = (x, y) => x + y;

// type 定义函数
type AddFnType = (a: number, b: number) => number;
const add2: AddFnType = (x, y) => x + y;

核心区别 ❌

1. 声明合并(interface 独有)

typescript 复制代码
// ✅ interface 支持声明合并,属性可以分头多次约束
interface Animal {
  name: string;
}
interface Animal {
  age: number;
}
const dog: Animal = { name: '三寸钉', age: 2 }

// ❌ type 不可以重复声明,同名会报错
type AnimalType = { name: string; }
// type AnimalType = { age: number; }  // Error

2. 联合类型与元组(type 独有)

typescript 复制代码
// ✅ type 支持联合类型
type ID = string | number;

// ✅ type 支持元组
type Point = [number, number];

// ❌ interface 不支持
// interface ID = string | number;  // 语法错误

对比表

特性 interface type
定义对象结构 ✅ ✅
继承 extends &
声明合并 ✅ ❌
联合类型 ❌ ✅
元组类型 ❌ ✅
函数类型 ✅ ✅

使用建议

场景 推荐
对象结构、Props interface
联合类型、元组 type
扩展第三方库 interface

面试回答

相同点: 都能定义对象结构,都支持继承,都能定义函数类型。

区别: interface 支持声明合并;type 支持联合类型、元组。

建议: 定义对象用 interface,联合类型用 type。

相关推荐
m0_587383008 分钟前
无人自助拼豆系统从需求分析到落地部署全流程实战开发指南
java·经验分享·后端·struts·小程序·架构·需求分析
a努力。10 分钟前
四维解析Agent记忆架构:从零实战LangGraph长期记忆
java·开发语言·数据库
碧海银沙音频科技研究院11 分钟前
炬芯ATS308X的扩音器:麦克风到扬声器直通功能实现
java·linux·运维
Rain的Java大神之路18 分钟前
被问麻了!Function Calling、MCP、Skill 到底啥关系?一张图讲透三层架构,附 Java 生产落地全流程+30个坑
java·后端·ai编程
Wang's Blog18 分钟前
Java 项目部署之 Docker工具快速入门: Docker Compose 初识与安装
java·开发语言·docker
niucloud-admin24 分钟前
JAVA V6 多商户商城 开发文档——项目启动
java·开发语言·python
31087487631 分钟前
0028.配置windows的共享目录让ubuntu使用
ubuntu·windows共享文件夹
众链网络41 分钟前
Agent 重试的工程解法:幂等、断点续跑与熔断怎么落地
java·前端·数据库·人工智能
Wang's Blog1 小时前
Java 项目部署之 Docker工具快速入门: 镜像命令从 pull 到 load 的完整实操
java·开发语言·docker
Wang's Blog1 小时前
Java 项目部署之 Docker工具快速入门: Docker 数据卷命令与挂载实操
java·开发语言·docker