# @buge/ts-units 中文文档

规范地址：https://npmcn.com/package/%40buge/ts-units/

版本：1\.2\.3
npm 元数据更新时间：2023-12-19T20:44:47.540Z
中文译文更新时间：2026-11-08T18:34:18.025Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40buge/ts-units
原文对照：https://npmcn.com/package/%40buge/ts-units/?lang=original
项目主页：https://github.com/buge/ts-units#readme
源码仓库：https://github.com/buge/ts-units

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：205 kB，192 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2021-08-25T13:53:45.451Z
- 最新版本发布：2023-12-19T20:44:47.403Z
- 近 30 天下载量：7090（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：6（近 12 个月 0 个）

## 中文简介

类型脚本的物理单位

## 安装

```sh
npm install @buge/ts-units
```

也可以使用：`pnpm add @buge/ts-units`、`yarn add @buge/ts-units`、`bun add @buge/ts-units`

## README

# 类型脚本的物理单位

[![CI Build](https://github.com/buge/ts-units/actions/workflows/node.js.yml/badge.svg)](https://github.com/buge/ts-units/actions/workflows/node.js.yml) [![npm version](https://badge.fury.io/js/@buge%2Fts-units.svg)](https://badge.fury.io/js/@buge%2Fts-units)

`@buge/ts-units` 是一个用于在 TypeScript 中建模已输入物理单元的软件包.

它允许你以安全的方式告诉用户你需要什么

```ts
function setTemperature(t: Temperature) {
  ...
}
```

让他们在有道理的单位工作

```ts
setTemperature(celsius(21.3));
```

单位可以很容易地互相转换

```ts
const t = celsius(21.3).in(fahrenheit);
```

比较

```ts
meters(1) < feet(4);
```

用于数学表达式

```ts
const length = meters(5).plus(centimeters(3));
const speed = length.per(seconds(2));
```

## 基本用途

从 npm 安装或使用您最喜欢的软件包管理器 :

```sh
npm install @buge/ts-units
```

仅使用内置单元申报数量:

```ts
import {Length, meters} from '@buge/ts-units/length';
const length: Length = meters(5);
```

见 [内建单位](https://npmcn.com/package/%40buge/ts-units/#readme-built-in-units) 下面是所有内置的概况 单位.

### 显示

数量提供a `toString()` 便于制造的方法 到字符串 :

```ts
celsius(23.1).toString(); // '23.1ºC'
```

对于自定义格式化,数量和符号可以很容易地从 数量 :

```ts
const temp = celsius(23.1);
const html =
  `<span class="amount">${temp.amount.toFixed(1)}</span>` +
  `<span class="symbol">${temp.unit.symbol}</span>`;
```

### 改划

数量很容易从一个单元转换到另一个单元 `in` 方法 :

```ts
const length = meters(5.3).in(feet);
const temp = celsius(23.1).in(fahrenheit);
```

数量(也许很明显)只能从属于 同样的物理维度,这样,但看 [乘法和分法](https://npmcn.com/package/%40buge/ts-units/#readme-multiplication-and-division) 以下为更多 高级转换.

### 比较

使用标准类型脚本可以自由比较数量 运算符( 谢谢 [`valueOf`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf):

```ts
meters(1) < feet(4);
```

由于浮点算术的精度不高,你应该更喜欢 使用该 `isCloseTo` 用于核对平等数量的方法:

```ts
// Returns whether 1m is within 0.01 feet of 3.28 feet.
meters(1).isCloseTo(feet(3.28), 0.01);
```

### 增减

同一物理维度的量可以自由添加 `plus` 财务报告和审定财务报表 使用 `minus`数字 :

```ts
const time = minutes(3).plus(seconds(2));
const length = meters(5).minus(feet(1));
```

归还数量单位默认为数量单位 增减.

### 乘法和分法

数量可以乘以 `times` 与 `per`,导致 返回新尺寸 :

```ts
const area: Area = meters(5).times(meters(6));
const speed: Speed = kilometers(150).per(hours(2));
```

特例是无尺寸单位的乘法,导致 返回的同一单位:

```ts
const length: Length = meters(5).times(percent(10)); // 0.5m
```

您可以平方和立方体的数量并取出它们的对等:

```ts
const area: Area = meters(3).squared();
const volume: Volume = meters(2).cubed();
const frequency: Frequency = seconds(3).reciprocal();
```

您可以使用量之间的关系来定义单位转换:

```ts
const riceDensity = grams(220).per(cups);
const iNeed = grams(500).per(riceDensity).in(ounces);
```

## 内建单位

以下是目前我们所建图书馆所有单位的参考文献.

### 平面角

```ts
import {Angle, degrees, sin} from '@buge/ts-units/angle';
const angle: Angle = degrees(30);
const s = sin(angle);
```

**单位 :**  
弧度、度、转弯

**三角函数 :**  
罪过,因为, 棕色, 相干, 相干,相干,相干,相干,相干

### 固态角

```ts
import {SolidAngle, steradians} from '@buge/ts-units/angle/solid';
const angle: SolidAngle = steradians(1);
```

**单位 :**  
结扎剂,平方

### 区域

```ts
import {Area, squareMeters} from '@buge/ts-units/area';
const area: Area = squareMeters(15);
```

**单位 :**  
平方米数

### 电容

```ts
import {Capacitance, microfarads} from '@buge/ts-units/eletric/capacitance';
const capacitance: Capacitance = microfarads(4700);
```

**单位 :**  
地平面、微地平面、纳米地平面、地平面

### 电费

```ts
import {Charge, coulombs} from '@buge/ts-units/eletric/charge';
const charge: Charge = coulombs(5000);
```

**单位 :**  
库伦布

### 电导

```ts
import {Conductance, siemens} from '@buge/ts-units/eletric/conductance';
const conductance: Conductance = siemens(0.2);
```

**单位 :**  
锡门

### 电流

```ts
import {Current, amperes} from '@buge/ts-units/eletric/current';
const current: Current = amperes(10);
```

**单位 :**  
闪光灯

### 电导

```ts
import {Inductance, henries} from '@buge/ts-units/eletric/inductance';
const inductance: Inductance = henries(1);
```

**单位 :**  
母鸡

### 电阻

```ts
import {Resistance, ohms} from '@buge/ts-units/eletric/resistance';
const resistance: Resistance = ohms(560);
```

**单位 :**  
欧姆斯

### 电压

```ts
import {Voltage, volts} from '@buge/ts-units/eletric/voltage';
const voltage: Voltage = volts(220);
```

**单位 :**  
电压

### 能源

```ts
import {Energy, joules} from '@buge/ts-units/energy';
const energy: Energy = joules(4.1868);
```

**单位 :**  
焦数

### 强制

```ts
import {Force, newtons} from '@buge/ts-units/force';
const force: Force = newtons(608);
```

**单位 :**  
牛顿

### 频率

```ts
import {Frequency, hertz} from '@buge/ts-units/force';
const frequency: Frequency = hertz(608);
```

**单位 :**  
赫兹

### 长度

```ts
import {Length, meters} from '@buge/ts-units/length';
const length: Length = meters(5);
```

**计量单位 :**  
公尺、公里、厘米、毫米、微米、纳米、, 相位计、相位计、相位计、相位计、相位计、相位计

**帝国单位 :**  
码、尺、寸、链、毛、里

**陆战队:**  
鱼相、海米斯

**天文单位:**  
天文单位

### 豪华豪华

```ts
import {Flux, lumes} from '@buge/ts-units/luminous/flux';
const flux: Flux = lumens(800);
```

**单位 :**  
灯泡

### 光辉

```ts
import {Illuminance, lux} from '@buge/ts-units/luminous/illuminance';
const illuminance: Illuminance = lux(35000);
```

**单位 :**  
豪华

### 令人发指的强度

```ts
import {Intensity, candelas} from '@buge/ts-units/luminous/intensity';
const intensity: Intensity = candelas(135);
```

**单位 :**  
加拿大语name

### 磁通量

```ts
import {Flux, webers} from '@buge/ts-units/magnetic/flux';
const flux: Flux = webers(800);
```

**单位 :**  
网页

### 质量

```ts
import {Mass, kilograms} from '@buge/ts-units/mass';
const mass: Mass = kilograms(5);
```

**单位 :**  
克(克)公斤

### 斯卡尔

从技术上讲,它不是一个物理层面,但仍然非常有用.

```ts
import {Scalar, percent} from '@buge/ts-units/scalar';
const scalar: Scalar = percent(20);
```

**单位 :**  
百分数,百分数,百分数

### 速度

```ts
import {Speed, metersPerSecond} from '@buge/ts-units/speed';
const speed: Speed = metersPerSecond(343);
```

**单位 :**  
秒,公里,英里,节,脚,秒

### 权力

```ts
import {Power, watts} from '@buge/ts-units/power';
const power: Power = watts(800);
```

**单位 :**  
瓦特

### 压力

```ts
import {Pressure, pascals} from '@buge/ts-units/pressure';
const pressure: Pressure = pascals(101325);
```

**单位 :**  
帕斯卡尔

### 放射性

```ts
import {Radioactivity, becquerels} from '@buge/ts-units/radioactive/decay';
const radioactivity: Radioactivity = becquerels(20);
```

**单位 :**  
饼干

### 吸收和等离子辐射剂量

```ts
import {Dose, grays, sieverts} from '@buge/ts-units/radioactive/dose';
const absorbed: Dose = grays(20e-6);
const equivaelnt: Dose = sieverts(1.5e-3);
```

**单位 :**  
灰色, 斜体

### 温度

```ts
import {Temperature, celsius} from '@buge/ts-units/temperature';
const temperature: Temperature = celsius(23.1);
```

**单位 :**  
kelvin, celsius, fahrenheit, calkin (法语)

### 时间

```ts
import {Time, minutes} from '@buge/ts-units/time';
const time: Time = minutes(5);
```

**单位 :**  
秒,毫秒(毫秒),微秒(用克),纳米秒,分数,小时

### 数量

```ts
import {Volume, cubicMeters} from '@buge/ts-units/volume';
const volume: Volume = cubicMeters(3);
```

**单位 :**  
立方块

## 界定新单位

现有维度的新单位可以轻而易举地在以下基础上加以界定: 现有。 例如,这里对院子的定义是:

```ts
const yards: Unit<Length> = meters.times(0.9144).withSymbol('yd');
```

类似量可以乘以和相分,你可以创建新的衍生 通过使用 `time`,用 `per`时 它们使用 `squared`,使用 `cubed` 并相互使用 `reciprocal`。 。 。 .

```ts
const knots: Unit<Speed> = nauticalMiles.per(hours).withSymbol('kn');
const mps2: Unit<Acceleration> = meters
  .per(seconds.squared())
  .withSymbol('m/s²');
```

如上所示,您可以使用 `withSymbol` 后缀为使用 `toString()`。可以提供任意字符串。 符号可以检索 从单位使用 `.symbol` 或从使用数量 `.unit.symbol`。 。 。 .

我们提供一种专用的方法 来创建配有 SI 前缀的衍生单元 两者 缩放单位并预置符号前缀.

```ts
const micrograms = gram.withSiPrefix('μ');
micrograms(2.13).toString(); // 2.13μg
```

支持的 SI 前缀在 `unit.SiPrefix`。 。 。 .

## 定义新维度

我们为所有职业分类基础单位和许多衍生单位提供单位和尺寸 单位。 这些可以作为界定许多其他单位的构件.

有时你会发现自己想要定义新物质的单位,或者 “东西”虽然.

可计量的事物通过“分数”来定义。 在科学文献中a 维度往往用大写字母和方括号表示。 对于 例如,长度的维度通常指: `[L]`,则 区域为 `[L]2` 和速度作为 `[L][T]-1`。 。 。 .

通过将单位尺寸和数量编码为 [脚本文字类型](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#literal-types)。 。 。 . 例如,上述层面的定义是:

```ts
type Length = {length: 1};
type Area = {length: 2};
type Speed = {length: 1; time: -1};
```

要定义一个新的维度,首先要定义它的字面类型. 你会的 还需要为它定义一个可在运行时使用的常数,因为 TypeScript 类型在编译后全部消失. 例如,如果你愿意的话 介绍你可能写多少钱:

```ts
// In money/dimension.ts
export type Money = {money: 1};
export const Money: Money = {money: 1};
```

我们使用一个公约,我们使用同样的资本 对于类型和用于 因为它让我们(在大多数情况下)忘记了 无论我们使用的类型还是值。 我们还把维度放在 `dimension.ts` 并肩作战,这样我们才能分辨 `Length` 作为 维度对 a `Length` 作为数量.

接下来,您要定义维度的基础单位 。 让我们来拿 美元作为基数单位:

```ts
// In money/units.ts
import * as dimension from './dimension';
export type Money = Quantity<number, dimension.Money>;
export const dollars: Unit<number, dimension.Money> = makeUnit('$', dimension.Money);
```

您现在可以使用您的新尺寸和单位定义数量 :

```ts
const pleaseDonateToACharityOfYourChoice: Money = usd(10);
```

## 定义新算术

由库提供的默认单位都是基于JavaScript号码的原生代表,这可能导致精确错误. 最出名的例子是(0.1+0.2).

图书馆为您提供了实施自己的算术的可能性,从而提供了避免这一问题的方法. 每组单位都会暴露一个功能 `withValueType` 使用自己的算术返回单位.

具体来说,您可以使用其他外部图书馆,这些图书馆可以提供更强大的数字代表. 比如说 [小数点.js](https://github.com/MikeMcl/decimal.js)数字 :

```ts
import {Arithmetic, Geometric} from "@buge/ts-units";
import {Decimal } from 'decimal.js';
import {withValueType as temperatureWithValueType} from '@buge/ts-units/temperature';
import {withValueType as angleWithValueType} from '@buge/ts-units/angle';

const DecimalArithmetic: Arithmetic<Decimal> = {
  fromNative(value: number): Decimal {
    return new Decimal(value);
  },
  toNative(value: Decimal): number {
    return value.toNumber();
  }
  add(left: Decimal, right: Decimal): Decimal {
    return left.add(right);
  },
  sub(left: Decimal, right: Decimal): Decimal {
    return left.sub(right);
  },
  mul(left: Decimal, right: Decimal): Decimal {
    return left.mul(right);
  },
  div(left: Decimal, right: Decimal): Decimal {
    return left.div(right);
  },
  pow(base: Decimal, exponent: Decimal): Decimal {
    return base.pow(exponent);
  },
  abs(value: Decimal): Decimal {
    return value.abs();
  },
  compare(left: Decimal, right: Decimal): number {
    return left.comparedTo(right);
  }
};

const {celsius} = temperatureWithValueType(DecimalArithmetic);

// Planar Angles needs also an implementation of geometric.
const DecimalGeometric: Geometric<Decimal> = {
    sin(value: Decimal): Decimal {
        return value.sin();
    },
    cos(value: Decimal): Decimal {
        return value.cos();
    },
    tan(value: Decimal): Decimal {
        return value.tan();
    },
    asin(value: Decimal): Decimal {
        return value.asin();
    },
    acos(value: Decimal): Decimal {
        return value.acos();
    },
    atan(value: Decimal): Decimal {
        return value.atan();
    },
    atan2(left: Decimal, right: Decimal): Decimal {
        return Decimal.atan2(left, right);
    }
};

const {radians, sin, cos} = angleWithValueType(DecimalArithmetic, DecimalGeometric);
```

最后,如果你想用自己的算术从头创建自己的单位,可以使用函数 `makeUnitFactory`。 。 。 .

```ts
import * as dimension from './dimension';
import {DecimalArithmetic} from './arithmetic'

const {makeUnit} = makeUnitFactory(DecimalArithmetic);

export type Money = Quantity<Decimal, dimension.Money>;
export const dollars: Unit<Decimal, dimension.Money> = makeUnit('$', dimension.Money);
```

## 限制

### 缺乏类型

两种类型如果具有相同的维度,是相容的. 也就是说,他们可以 减为相同的基数单位等同。 这可能意味着一些事情 当实际不应是:

```ts
setFrequency(hertz(100));
setFrequency(becquerels(100));

radiationAlarm(grays(2));
radiationAlarm(sieverts(2));
```

_ISO 80000-1:2009(英)_ 把它们定义为单独的“种类”,但我们目前 无法在编译时检查数量 运行时间.

在某些情况下,我们冒昧地将数量模拟为 不同的单位,具体带有平面角度和固体角度. 虽然这些 严格来说是无尺寸的 `[L]/[L]` 财务报告和审定财务报表 `[L]^2/[L]^2` 我们分别将这些模型作为:

```ts
type Angle = {angle: 1};
type SolidAngle = {angle: 2};
```

### 缺乏投入的灵活性

目前,您在声明数量时只能使用本地数字作为输入 .

```ts
import {meters} from '@buge/ts-units/length';
// It won't work
const length = meters('5');
```

```ts
import {withValueType} from '@buge/ts-units/length';
const { meters } = withValueType(DecimalArithmetic);
// It won't work
const length = meters(new Decimal(5));
```

此外,计算功能是: `Unit` 财务报告和审定财务报表 `Quantity` 还只支持本地号码.

将来还可以改进

## 常见问题

### @buge/ts-units 是什么？

类型脚本的物理单位

### 如何安装 @buge/ts-units？

在项目目录运行 npm install @buge/ts-units，或使用 pnpm add / yarn add / bun add。

### @buge/ts-units 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @buge/ts-units 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @buge/ts-units 可以商用吗？

@buge/ts-units 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @buge/ts-units 的下载量有多少？

根据 npm 官方下载统计，@buge/ts-units 在 2026/10/09 – 2026/11/07 这 30 天内被下载 7,090 次，日均约 236 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @buge/ts-units 还在维护吗？

最新版本 1\.2\.3 发布于 2023/12/20（2 年前）；至今共发布 6 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/08/25。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

