& 把多个类型合并成一个:新类型拥有全部成员,常用于混入(mixin)与接口扩展。 & 把多个类型合并成一个:新类型拥有全部成员,常用于混入(mixin)与接口扩展。 & 把多个类型合并成一个:新类型拥有全部成员,常用于混入(mixin)与接口扩展。
TypeScript 词条目录
前端Wiki/TypeScript/进阶/联合与交叉类型

交叉类型与类型别名

交叉类型用 & 把多个类型合并成一个:新类型拥有全部成员,常用于混入(mixin)与接口扩展。type 别名与 interface 都能描述对象形状,选哪个主要是风格问题。

能力上的差别:interface 能被 class implements、同名声明会自动合并叠加;type 能写联合、交叉、原始类型别名、工具类型。公共 API 与可扩展结构建议 interface,组合运算建议 type。

  • 交叉类型 A & B:同时满足 A 和 B,用于合并形状
  • type 能写联合/交叉/原始别名;interface 只描述对象
  • 同名 interface 自动合并,同名 type 报重复定义
TS
interface Person { name: string }
interface Logged { loginAt: Date }
// 交叉类型:既是 Person 又是 Logged
type User2 = Person & Logged;
const u: User2 = { name: '小明', loginAt: new Date() };

// interface 同名声明自动合并(type 不行)
interface Point { x: number }
interface Point { y: number }
const p: Point = { x: 1, y: 2 };   // 合并成 {x, y}

// type 的主场:联合、交叉、原始别名
type ID = number | string;
type Callback = (n: number) => void;
type DeepReadonly<T> = { readonly [K in keyof T]: T[K] };
JS
// 类型与别名全部擦除
const u = { name: '小明', loginAt: new Date() };
console.log(u.name, u.loginAt instanceof Date);   // 小明 true

const p = { x: 1, y: 2 };
console.log(p);    // { x: 1, y: 2 }
本节要点交叉类型做合并,interface 与 type 按场景选:扩展用 interface,组合用 type。
🔗 相关词条JavaScriptCSSReact