This repository has been archived by the owner on Jan 7, 2020. It is now read-only.
/
typeOf.ts
62 lines (52 loc) · 2.14 KB
/
typeOf.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// tslint:disable:ban-types
export interface IIndexedObject { [key: string]: any }
export interface ITypeOf {
(value: any): string
isBoolean: (value: any) => value is boolean
isNull: (value: any) => value is null
isUndefined: (value: any) => value is undefined
isString: (value: any) => value is string
isNumber: (value: any) => value is number
isSymbol: (value: any) => value is symbol
isFunction: (value: any) => value is Function
isArray: <O = any[]>(value: any) => value is O
isObject: <O = IIndexedObject>(value: any) => value is O
isRegExp: (value: any) => value is RegExp
isDate: (value: any) => value is Date
}
// Primitives
export const isBoolean = (value): value is boolean => typeof value === 'boolean'
export const isNull = (value): value is null => value === null
export const isUndefined = (value): value is undefined => value === undefined
export const isString = (value): value is string => typeof value === 'string'
export const isNumber = (value): value is number => typeof value === 'number' && !isNaN(value)
export const isSymbol = (value): value is symbol => typeof value === 'symbol'
// Object obfuscated types
export const isFunction = (value): value is Function => typeof value === 'function'
export const isArray = <O = any[]>(value): value is O => Array.isArray(value)
export const isObject = <O = IIndexedObject>(value): value is O => typeOf(value) === 'object'
export const isRegExp = (value): value is RegExp => typeOf(value) === 'regexp'
export const isDate = (value): value is Date => typeOf(value) === 'date'
export const typeOf: ITypeOf = (() => {
const toString = Object.prototype.toString
const fn: any = (value: any): string => {
// For performance
if (typeof value === 'number' && isNaN(value)) { return 'nan' }
const type = toString.call(value)
.slice(8, -1)
.toLowerCase()
return type
}
fn.isBoolean = isBoolean
fn.isNull = isNull
fn.isUndefined = isUndefined
fn.isString = isString
fn.isNumber = isNumber
fn.isSymbol = isSymbol
fn.isFunction = isFunction
fn.isArray = isArray
fn.isObject = isObject
fn.isRegExp = isRegExp
fn.isDate = isDate
return fn
})()