Skip to content

Instantly share code, notes, and snippets.

@flavioespinoza
Created February 21, 2019 15:56
Show Gist options
  • Save flavioespinoza/8685b29314f1ae3bdafb9e3691ec0880 to your computer and use it in GitHub Desktop.
Save flavioespinoza/8685b29314f1ae3bdafb9e3691ec0880 to your computer and use it in GitHub Desktop.
TypeScript Integer Types
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