Safe Units
Safe Units is a type safe library for using units of measurement in TypeScript. Safe Units provides an implementation of an SI based unit system but is flexible enough to allow users to create their own unit systems which can be independent or can interoperate with the built-in units. Users can also make unit systems for any numeric type they'd like not just the JavaScript number
type. This library requires TypeScript 3.2 or higher.
; ;;; console.loglength.toString; // 30 mconsole.logtime.toString; // 15 sconsole.logvelocity.toString; // 2 m * s^-1 ;// ERROR: A measure of m*s isn't assignable to a measure of m/s.
Features
⭐ Compile-time unit arithmetic for typesafe dimensional analysis (with exponents between -5 and +5)!
⭐ Large library of predefined units including metric (with prefixes), Imperial, and US customary units!
⭐ Ability to add your own unit system that can work with built-in units!
⭐ Long build times & cryptic error messages!
Prerequisites
Safe units is written in TypeScript and should be consumed by TypeScript users to take full advantage of what it provides. In addition you will need the following:
- TypeScript 3.2 or later
- Strict null checks enabled for your project
Installation
npm install safe-units
or
yarn add safe-units
Examples
Unit arithmetic
; ;;;; // 5 m ;;; ; // 294 N; // 49 Pa; // 0.5 mbarpressure.ltmaxPressure // true
Type errors
; ;; length.plustime;// ERROR: Measures of different units cannot be added length.minustime;// ERROR: Measures of different units cannot be subtracted ;// ERROR: Measure of m/s is not assignable to measure of kg*m/s^2 ;// ERROR: Can't take sqrt of measure of m since it's not a perfect square
Naming units
; ; console.logMeasure.of8, furlongs.inmiles; // 1 miconsole.logMeasure.of1, miles.infurlongs; // 8 fur ; .permicrofortnights .withSymbol"Mfur/µftn"; console.logspeedOfLight.inmegaFurlongsPerMicroFortnight; // 1.8026174997852542 Mfur/µftn
Deriving quantities
; ;; ;;; console.logjerk.toString; // 4.9 m * s^-3
Defining dimensions
; ; ;; ;; ; ; ;;; if measuredFps.ltminFrameRate