is WhatJS 类型检查工具
is What 是一个非常简单且小巧的 JS 类型检查功能,它同样完全支持 TypeScript
npm i is-what
用法
is-what 很容易使用,并且大多数功能都可以像你所期望的那样工作。
// import functions you want to use like so:
import { isString, isDate, isPlainObject } from 'is-what'
简单的类型检查函数
// basics
isBoolean(true) // true
isBoolean(false) // true
isUndefined(undefined) // true
isNull(null) // true
// strings
isString('') // true
isEmptyString('') // true
isFullString('') // false
// numbers
isNumber(0) // true
isNumber('0') // false
isNumber(NaN) // false *
isPositiveNumber(1) // true
isNegativeNumber(-1) // true
// * see below for special NaN use cases!
// arrays
isArray([]) // true
isEmptyArray([]) // true
isFullArray([1]) // true
// objects
isPlainObject({}) // true *
isEmptyObject({}) // true
isFullObject({ a: 1 }) // true
// * see below for special object (& class instance) use cases!
// functions
isFunction(function () {}) // true
isFunction(() => {}) // true
// dates
isDate(new Date()) // true
isDate(new Date('invalid date')) // false
// maps & sets
isMap(new Map()) // true
isSet(new Set()) // true
isWeakMap(new WeakMap()) // true
isWeakSet(new WeakSet()) // true
// others
isRegExp(/\\\\\\\\\\\\\\\\s/gi) // true
isSymbol(Symbol()) // true
isBlob(new Blob()) // true
isFile(new File([''], '', { type: 'text/html' })) // true
isError(new Error('')) // true
isPromise(new Promise((resolve) => {})) // true
// primitives
isPrimitive('') // true
// true for any of: boolean, null, undefined, number, string, symbol
NaN
isNaN 是一个内置的 JS 函数:
// 1)
typeof NaN === 'number' // true
// 🤔 ("not a number" is a "number"...)
// 2)
isNaN('1') // false
// 🤔 the string '1' is not-"not a number"... so it's a number??
// 3)
isNaN('one') // true
// 🤔 'one' is NaN but `NaN === 'one'` is false...
使用 is-what 我们对待 NaN 的方式更有意义一点:
import { isNumber, isNaNValue } from 'is-what'
// 1)
isNumber(NaN) // false!
// let's not treat NaN as a number
// 2)
isNaNValue('1') // false
// if it's not NaN, it's not NaN!!
// 3)
isNaNValue('one') // false
// if it's not NaN, it's not NaN!!
isNaNValue(NaN) // true
获取和检查特定类型
可以使用getType和检查特定类型isType:
import { getType, isType } from 'is-what'
getType('') // returns 'String'
// pass a Type as second param:
isType('', String) // returns true
评论
