This is the top result on Google for me so I figure I should provide the solutions I found.
Using bigint
Now that it's 2020 and bigint
has been accepted, it deserves a mention. You can simply do the below. Beware that bigint
s come with a bigger performance impact compared to a number
.
const myNumber: bigint = 10n
Using a nominal type / tagged type / opaque type
An alternative is to use a nominal type, but it's arguably less ergonomic and I'm not sure if it's any faster than bigint
, but the pattern does generalise to any type, not just number
. TypeScript doesn't have "first-class" support for this so you have to do a cheeky hack. There's a library for this called newtype-ts
that includes common types like Integer
so you might just want to just use that, but I'll explain the workings below.
To start out with we define the integer
type.
const TAG = Symbol()
type integer = number & { readonly [TAG]: unique symbol }
The TAG
ensures we have a unique value so that we don't accidentally make an object with the same key, and we make the field a unique symbol too for the same reason. Now, your integer won't actually have this object field but that's fine.
With this you can still add integer
to number
using +
. Not good. So you can enforce type safety on the arguments here by massaging the type system with a function. I'm just gonna call it guard, and again as you can see it isn't specific to integer
s – you could make more opaque types and use this again.
type guard = <A>(f: (...ns: Array<A>) => A, ...ns: Array<A>) => A
const guard: guard = (f, ...ns) => f(...ns)
If you try to call that with a number
const bad: integer = guard((a, b) => a + b as integer, myCoolInteger, 10)
you'll get an error like below
Argument of type '10' is not assignable to parameter of type 'integer'.
Type '10' is not assignable to type '{ readonly [TAG]: unique symbol; }'.(2345)
Note that you aren't enforcing the return type here (because you have to use as integer
) and some operators like /
will return floating point numbers so you probably still want to do runtime checks or add a Math.round
to a specialised version of guard
, but this will at least ensure you're not trying to use two separate numeric types together – imagine you have GBP
and USD
and try to add those, that would likely not be what you intended.
if (someNumber % 1 === 0) // then it is an integer
in either case this approach can be dangerous as the consumer will not be made aware of this change taking place which could lead to unexpected results. it might be better to throw an error if an int is required but float was input.