Skip to content

Newtype 模式

一句话解释

Newtype 从现有类型创建不同类型——相同运行时值,不同编译时类型。

用大白话说

Newtype 模式(来自 Haskell)创建包装现有类型的新类型,赋予其独特身份而无运行时开销。type Celsius = number & { readonly _tag: "Celsius" } type Fahrenheit = number & { readonly _tag: "Fahrenheit" }

运行时两者都只是数字。编译时它们是不同的——你不能意外地将摄氏度和华氏度相加。这类似于品牌类型,但专门用于从原始类型创建新类型。用例:度量单位、ID、领域特定包装。Newtype 与底层类型有相同性能——无装箱、无分配。

示例

typescript
type Celsius = number & { readonly _tag: "Celsius" };
type Fahrenheit = number & { readonly _tag: "Fahrenheit" };

const celsius = (n: number): Celsius => n as Celsius;
const fahrenheit = (n: number): Fahrenheit => n as Fahrenheit;

function toFahrenheit(c: Celsius): Fahrenheit {
  return fahrenheit((c as number) * 9/5 + 32);
}

const temp = celsius(100);
const converted = toFahrenheit(temp); // Fahrenheit
// temp + converted; // Error! Can't mix Celsius and Fahrenheit

Celsius 和 Fahrenheit 运行时都是数字但编译时是不同类型。不能在没有显式转换的情况下混用。

常见混淆

  • 容易混淆的对象: 品牌类型

    关键区别: 品牌类型和 Newtype 在 TypeScript 中本质上是相同的模式——都使用与幻影属性的交集。术语 'Newtype' 来自 Haskell,在那里它创建真正的新类型。在 TypeScript 中,两者都用交集类型相同地实现。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表