市场夺宝奇兵
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

294 lines
8.3 KiB

  1. # is What? 🙉
  2. <a href="https://www.npmjs.com/package/is-what"><img src="https://img.shields.io/npm/v/is-what.svg" alt="Total Downloads"></a>
  3. <a href="https://www.npmjs.com/package/is-what"><img src="https://img.shields.io/npm/dw/is-what.svg" alt="Latest Stable Version"></a>
  4. Very simple & small JS type check functions. It's fully TypeScript supported!
  5. ```
  6. npm i is-what
  7. ```
  8. Or for deno available at: `"deno.land/x/is_what"`
  9. > Also check out [is-where 🙈](https://github.com/mesqueeb/is-where)
  10. ## Motivation
  11. I built is-what because the existing solutions were all too complex or too poorly built.
  12. I was looking for:
  13. - A simple way to check any kind of type (including non-primitives)
  14. - Be able to check if an object is a plain object `{}` or a special object (like a class instance) ‼️
  15. - Let TypeScript automatically know what type a value is when checking
  16. And that's exactly what `is-what` is! (what a great wordplay 😃)
  17. ## Usage
  18. is-what is really easy to use, and most functions work just like you'd expect.
  19. ```js
  20. // import functions you want to use like so:
  21. import { isString, isDate, isPlainObject } from 'is-what'
  22. ```
  23. 1. First I'll go over the simple functions available. Only `isNumber` and `isDate` have special treatment.
  24. 2. After that I'll talk about working with Objects (plain objects vs class instances etc.).
  25. 3. Lastly I'll talk about TypeScript implementation
  26. ### Simple type check functions
  27. ```js
  28. // basics
  29. isBoolean(true) // true
  30. isBoolean(false) // true
  31. isUndefined(undefined) // true
  32. isNull(null) // true
  33. // strings
  34. isString('') // true
  35. isEmptyString('') // true
  36. isFullString('') // false
  37. // numbers
  38. isNumber(0) // true
  39. isNumber('0') // false
  40. isNumber(NaN) // false *
  41. isPositiveNumber(1) // true
  42. isNegativeNumber(-1) // true
  43. // * see below for special NaN use cases!
  44. // arrays
  45. isArray([]) // true
  46. isEmptyArray([]) // true
  47. isFullArray([1]) // true
  48. // objects
  49. isPlainObject({}) // true *
  50. isEmptyObject({}) // true
  51. isFullObject({ a: 1 }) // true
  52. // * see below for special object (& class instance) use cases!
  53. // functions
  54. isFunction(function () {}) // true
  55. isFunction(() => {}) // true
  56. // dates
  57. isDate(new Date()) // true
  58. isDate(new Date('invalid date')) // false
  59. // maps & sets
  60. isMap(new Map()) // true
  61. isSet(new Set()) // true
  62. isWeakMap(new WeakMap()) // true
  63. isWeakSet(new WeakSet()) // true
  64. // others
  65. isRegExp(/\s/gi) // true
  66. isSymbol(Symbol()) // true
  67. isBlob(new Blob()) // true
  68. isFile(new File([''], '', { type: 'text/html' })) // true
  69. isError(new Error('')) // true
  70. isPromise(new Promise((resolve) => {})) // true
  71. // primitives
  72. isPrimitive('') // true
  73. // true for any of: boolean, null, undefined, number, string, symbol
  74. ```
  75. ### Let's talk about NaN
  76. `isNaN` is a built-in JS Function but it really makes no sense:
  77. ```js
  78. // 1)
  79. typeof NaN === 'number' // true
  80. // 🤔 ("not a number" is a "number"...)
  81. // 2)
  82. isNaN('1') // false
  83. // 🤔 the string '1' is not-"not a number"... so it's a number??
  84. // 3)
  85. isNaN('one') // true
  86. // 🤔 'one' is NaN but `NaN === 'one'` is false...
  87. ```
  88. With is-what the way we treat NaN makes a little bit more sense:
  89. ```js
  90. import { isNumber, isNaNValue } from 'is-what'
  91. // 1)
  92. isNumber(NaN) // false!
  93. // let's not treat NaN as a number
  94. // 2)
  95. isNaNValue('1') // false
  96. // if it's not NaN, it's not NaN!!
  97. // 3)
  98. isNaNValue('one') // false
  99. // if it's not NaN, it's not NaN!!
  100. isNaNValue(NaN) // true
  101. ```
  102. ### isPlainObject vs isAnyObject
  103. Checking for a JavaScript object can be really difficult. In JavaScript you can create classes that will behave just like JavaScript objects but might have completely different prototypes. With is-what I went for this classification:
  104. - `isPlainObject` will only return `true` on plain JavaScript objects and not on classes or others
  105. - `isAnyObject` will be more loose and return `true` on regular objects, classes, etc.
  106. ```js
  107. // define a plain object
  108. const plainObject = { hello: 'I am a good old object.' }
  109. // define a special object
  110. class SpecialObject {
  111. constructor(somethingSpecial) {
  112. this.speciality = somethingSpecial
  113. }
  114. }
  115. const specialObject = new SpecialObject('I am a special object! I am a class instance!!!')
  116. // check the plain object
  117. isPlainObject(plainObject) // returns true
  118. isAnyObject(plainObject) // returns true
  119. getType(plainObject) // returns 'Object'
  120. // check the special object
  121. isPlainObject(specialObject) // returns false !!!!!!!!!
  122. isAnyObject(specialObject) // returns true
  123. getType(specialObject) // returns 'Object'
  124. ```
  125. > Please note that `isPlainObject` will only return `true` for normal plain JavaScript objects.
  126. ### Getting and checking for specific types
  127. You can check for specific types with `getType` and `isType`:
  128. ```js
  129. import { getType, isType } from 'is-what'
  130. getType('') // returns 'String'
  131. // pass a Type as second param:
  132. isType('', String) // returns true
  133. ```
  134. If you just want to make sure your object _inherits_ from a particular class or
  135. `toStringTag` value, you can use `isInstanceOf()` like this:
  136. ```js
  137. import { isInstanceOf } from 'is-what'
  138. isInstanceOf(new XMLHttpRequest(), 'EventTarget')
  139. // returns true
  140. isInstanceOf(globalThis, ReadableStream)
  141. // returns false
  142. ```
  143. ## TypeScript
  144. is-what makes TypeScript know the type during if statements. This means that a check returns the type of the payload for TypeScript users.
  145. ```ts
  146. function isNumber(payload: any): payload is number {
  147. // return boolean
  148. }
  149. // As you can see above, all functions return a boolean for JavaScript, but pass the payload type to TypeScript.
  150. // usage example:
  151. function fn(payload: string | number): number {
  152. if (isNumber(payload)) {
  153. // ↑ TypeScript already knows payload is a number here!
  154. return payload
  155. }
  156. return 0
  157. }
  158. ```
  159. `isPlainObject` and `isAnyObject` with TypeScript will declare the payload to be an object type with any props:
  160. ```ts
  161. function isPlainObject(payload: any): payload is { [key: string]: any }
  162. function isAnyObject(payload: any): payload is { [key: string]: any }
  163. // The reason to return `{[key: string]: any}` is to be able to do
  164. if (isPlainObject(payload) && payload.id) return payload.id
  165. // if isPlainObject() would return `payload is object` then it would give an error at `payload.id`
  166. ```
  167. ### isObjectLike
  168. If you want more control over what kind of interface/type is casted when checking for objects.
  169. To cast to a specific type while checking for `isAnyObject`, can use `isObjectLike<T>`:
  170. ```ts
  171. import { isObjectLike } from 'is-what'
  172. const payload = { name: 'Mesqueeb' } // current type: `{ name: string }`
  173. // Without casting:
  174. if (isAnyObject(payload)) {
  175. // in here `payload` is casted to: `Record<string | number | symbol, any>`
  176. // WE LOOSE THE TYPE!
  177. }
  178. // With casting:
  179. // you can pass a specific type for TS that will be casted when the function returns
  180. if (isObjectLike<{ name: string }>(payload)) {
  181. // in here `payload` is casted to: `{ name: string }`
  182. }
  183. ```
  184. Please note: this library will not actually check the shape of the object, you need to do that yourself.
  185. `isObjectLike<T>` works like this under the hood:
  186. ```ts
  187. function isObjectLike<T extends object>(payload: any): payload is T {
  188. return isAnyObject(payload)
  189. }
  190. ```
  191. ## Meet the family (more tiny utils with TS support)
  192. - [is-what 🙉](https://github.com/mesqueeb/is-what)
  193. - [is-where 🙈](https://github.com/mesqueeb/is-where)
  194. - [merge-anything 🥡](https://github.com/mesqueeb/merge-anything)
  195. - [check-anything 👁](https://github.com/mesqueeb/check-anything)
  196. - [remove-anything ✂️](https://github.com/mesqueeb/remove-anything)
  197. - [getorset-anything 🐊](https://github.com/mesqueeb/getorset-anything)
  198. - [map-anything 🗺](https://github.com/mesqueeb/map-anything)
  199. - [filter-anything ⚔️](https://github.com/mesqueeb/filter-anything)
  200. - [copy-anything 🎭](https://github.com/mesqueeb/copy-anything)
  201. - [case-anything 🐫](https://github.com/mesqueeb/case-anything)
  202. - [flatten-anything 🏏](https://github.com/mesqueeb/flatten-anything)
  203. - [nestify-anything 🧅](https://github.com/mesqueeb/nestify-anything)
  204. ## Source code
  205. It's litterally just these functions:
  206. ```js
  207. function getType(payload) {
  208. return Object.prototype.toString.call(payload).slice(8, -1)
  209. }
  210. function isUndefined(payload) {
  211. return getType(payload) === 'Undefined'
  212. }
  213. function isString(payload) {
  214. return getType(payload) === 'String'
  215. }
  216. function isAnyObject(payload) {
  217. return getType(payload) === 'Object'
  218. }
  219. // etc...
  220. ```
  221. See the full source code [here](https://github.com/mesqueeb/is-what/blob/production/src/index.ts).