You need to enable JavaScript to run this app. TypeScript中如何让两个同为number基础类型的自定义类型互不兼容
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中如何让两个同为number基础类型的自定义类型互不兼容

TypeScript 实现同基础类型自定义别名互不兼容的方案

TypeScript 默认使用结构类型系统,只要两个类型结构一致就会判定为互相兼容,要实现你要的类型隔离效果,可以用名义类型(Nominal Type)的实现技巧,常用两种方案:

方案1:品牌类型(Branded Type,轻量无运行时开销)

这是当前最通用的实现方式,仅在类型层面给基础类型附加唯一标记,不会产生运行时代码:

// 通用品牌类型工具
type Brand<BaseType, Tag extends string> = BaseType & { __brand: Tag };

// 定义你的两个不兼容类型
export type GlobalPortIndex = Brand<number, 'GlobalPortIndex'>;
export type TypePortIndex = Brand<number, 'TypePortIndex'>;

// 建议配套封装创建方法,避免业务代码里手动写类型断言
export function createGlobalPortIndex(index: number): GlobalPortIndex {
  return index as GlobalPortIndex;
}
export function createTypePortIndex(index: number): TypePortIndex {
  return index as TypePortIndex;
}

使用后的效果:

const gPort = createGlobalPortIndex(3000);
const tPort = createTypePortIndex(8080);

// 以下操作都会触发类型错误,符合你的要求
const testAssign: GlobalPortIndex = tPort;
function acceptGlobalPort(p: GlobalPortIndex) {}
acceptGlobalPort(tPort);

// 不影响正常的数值运算逻辑
console.log(gPort * 2 + 1);

注:__brand 仅存在于类型定义中,运行时不会生成这个属性,没有额外性能消耗

方案2:私有字段类实现严格名义类型

如果你需要更高的类型安全性,避免手动断言破坏类型隔离,可以用带私有字段的类实现,TS对私有字段有严格的类型校验:

export class GlobalPortIndex {
  // 私有标记,不同类的私有字段即使同名也不兼容
  #typeTag: void;
  constructor(public readonly value: number) {}
}

export class TypePortIndex {
  #typeTag: void;
  constructor(public readonly value: number) {}
}

这种方式运行时会生成真实类,需要通过 new 关键字创建实例,使用数值时要访问 .value 属性,但类型隔离更严格,不会被意外的类型断言突破。


内容的提问来源于stack exchange,提问作者Szabolcs Szekelyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 17:15:07