Skip to content

Commit

Permalink
feat: add type guards (#103)
Browse files Browse the repository at this point in the history
* feat: add type guards

add type guards to all isN functions

* fix: use unknown[] instead of any[] in isArray type guard
  • Loading branch information
matteosacchetto authored Oct 14, 2022
1 parent 1291be2 commit 7a8a959
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions src/typed.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,48 @@
export const isSymbol = (value: any) => {
export const isSymbol = (value: any): value is symbol => {
return !!value && value.constructor === Symbol
}

export const isArray = (value: any) => {
export const isArray = (value: any): value is unknown[] => {
return !!value && value.constructor === Array
}

export const isObject = (value: any) => {
export const isObject = (value: any): value is object => {
return !!value && value.constructor === Object
}

export const isFunction = (value: any) => {
export const isFunction = (value: any): value is Function => {
return !!(value && value.constructor && value.call && value.apply)
}

export const isString = (value: any) => {
export const isString = (value: any): value is string => {
return typeof value === 'string' || value instanceof String
}

export const isInt = (value: any) => {
export const isInt = (value: any): value is number => {
return isNumber(value) && value % 1 === 0
}

export const isFloat = (value: any) => {
export const isFloat = (value: any): value is number => {
return isNumber(value) && value % 1 !== 0
}

export const isNumber = (value: any) => {
export const isNumber = (value: any): value is number => {
try {
return Number(value) === value
} catch {
return false
}
}

export const isDate = (value: any) => {
export const isDate = (value: any): value is Date => {
return Object.prototype.toString.call(value) === "[object Date]"
}

export const isEmpty = (value: any) => {
if (value === true || value === false) return true
if (value === null || value === undefined) return true
if (isNumber(value)) return parseInt(value) === 0
if (isDate(value)) return isNaN(value)
if (isNumber(value)) return value === 0
if (isDate(value)) return isNaN(value.getTime())
if (isFunction(value)) return false
if (isSymbol(value)) return false
const length = (value as any).length
Expand Down

0 comments on commit 7a8a959

Please sign in to comment.