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。

相关推荐
Cosolar37 分钟前
监控指标全正常,订单接口从 80ms 涨到 4s 故障复盘
java·后端·面试
吴名氏.4 小时前
从零手写一个 AI Agent 框架(TypeScript 完整实现):Function Calling 循环、流式输出与错误恢复
人工智能·typescript·node.js·大模型·ai agent·functioncalling·llm 应用开发
木子欢儿9 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu
会编程的吕洞宾10 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
斯维赤10 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
stormsha10 小时前
库存 5,10 个并发各买 1 件:为什么最后不剩 -5 件
java·数据库·mysql
RobinXYuan11 小时前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
炸薯条!11 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
濮水大叔11 小时前
Cabloy/Zova 与 Next.js 的前端缓存差异
typescript·全栈·next.js
SimonKing12 小时前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员