primitive-types
v0.2.6
Published
TypeScript types for integers, UUIDs, characters, etc.
Readme
🔌 primitive-types
Expressive low-level TypeScript types for integers, UUIDs, characters, etc.
let age: uint = 22;
age = -1;
// ^ ❌ tsc(2322): Type '-1' is not assignable to type 'uint'.
let id: uuid = "01964bbf-a8b9-7710-9cea-3d6691b15689";
id = "abc-123";
// ^ ❌ tsc(2322): Type '"abc-123"' is not assignable to type 'uuid<v>'.[!TIP] Includes overloads and type-narrowing for built-ins like Math, Array, Date, Number, TypedArrays, and more.
💿 Install
Add package:
npm install primitive-types --save-devEnable types in tsconfig.json:
{
"compilerOptions": {
"types": [
"primitive-types"
]
}
}Types
Arithmetic operations
In JavaScript all numbers are stored as 64-bit floating-point numbers or a 32-bit
integers, and then represented as the dynamic number type.
The benefit of these opaque types is arithemetic is completely interchangable:
let a: uint8 = 10;
let b: int16 = -21_374;
let c: float64 = 4274.80;
let result = a * b / c;
// -50And in-place arithmetic will naturally coerce variables to the number type too:
function isOver18(value: int8) {
return value >= 18;
}
let age: int8 = 125;
isOver18(age)
age *= 2;
// 'age' is coerced to 'number'
isOver18(age);
// ^ ❌ tsc(2345): Argument of type 'number' is not assignable to parameter of type 'int8'.