Created
February 21, 2019 15:56
-
-
Save flavioespinoza/8685b29314f1ae3bdafb9e3691ec0880 to your computer and use it in GitHub Desktop.
TypeScript Integer Types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type Int = number & { __int__: void } | |
export const roundToInt = (num: number): Int => Math.round(num) as Int | |
export const toInt = (value: string): Int => { | |
return Number.parseInt(value) as Int | |
} | |
export const checkIsInt = (num: number): num is Int => num % 1 === 0 | |
export const assertAsInt = (num: number): Int => { | |
try { | |
if (checkIsInt(num)) { | |
return num | |
} | |
} catch (err) { | |
throw new Error(`Invalid Int value (error): ${num}`) | |
} | |
throw new Error(`Invalid Int value: ${num}`) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment