Skip to content

Instantly share code, notes, and snippets.

@dschnare
Created January 31, 2020 20:55
Show Gist options
  • Save dschnare/3c1af421d90784d95b06d19d327d21be to your computer and use it in GitHub Desktop.
Save dschnare/3c1af421d90784d95b06d19d327d21be to your computer and use it in GitHub Desktop.
A type checking function for JS
const check = (type, value) => {
if (typeof type !== 'string') {
throw new TypeError('Argument "type" must be a string')
}
const optional = /!\??$/.test(type)
const nullable = /\?!?$/.test(type)
type = type.replace(/!$|\?$/g, '').trim()
if (['null', 'undefined', ''].includes(type.toLowerCase())) {
throw Object.assign(
new Error(`Argument "type" invalid: ${value}`),
{ name: 'ArgumentError', value }
)
}
if (type[0] === '/') {
return typeof value === 'string' && new RegExp(
type.split('/').slice(1, -1).join('/'),
type.split('/').pop()
).test(value)
}
if (optional && value === undefined) {
return true
}
if (nullable && value === null) {
return true
}
switch (type) {
case 'number': return typeof value === 'number'
case 'Number': return value instanceof Number
case 'finite': return Number.isFinite(value)
case 'integer': return Number.isSafeInteger(value)
case 'uinteger': return Number.isSafeInteger(value) && value >= 0
case 'ufinite': return Number.isFinite(value) && value >= 0
case 'string': return typeof value === 'string'
case 'String': return value instanceof String
case 'boolean': return typeof value === 'boolean'
case 'Boolean': return value instanceof Boolean
case 'function': return typeof value === 'function'
case 'Function': return typeof value === 'function'
case 'Date': return value instanceof Date && !isNaN(value.getTime())
case 'Array': return Array.isArray(value)
case 'RegExp': return value instanceof RegExp
case 'Set': return value instanceof Set
case 'Map': return value instanceof Map
case 'Object': return Object(value) === value
case 'iterable': return Object(value) === value && typeof value[Symbol.iterator] === 'function'
default: return type === Object.prototype.toString.call(value).slice(8, -1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment