Detect Types

Register a function to generate runtime window type definitions.

  1. // ==UserScript==
  2. // @name Detect Types
  3. // @namespace https://github.com/SlashNephy
  4. // @version 0.1.0
  5. // @author SlashNephy
  6. // @description Register a function to generate runtime window type definitions.
  7. // @description:ja window の型定義を生成する関数を登録します。
  8. // @homepage https://scrapbox.io/slashnephy
  9. // @homepageURL https://scrapbox.io/slashnephy
  10. // @icon https://www.google.com/s2/favicons?sz=64&domain=*
  11. // @supportURL https://github.com/SlashNephy/userscripts/issues
  12. // @match https://*/*
  13. // @grant unsafeWindow
  14. // @license MIT license
  15. // ==/UserScript==
  16.  
  17. (function () {
  18. 'use strict';
  19.  
  20. const escapeKey = (key) => {
  21. if (key.includes('.')) {
  22. return `'${key}'`;
  23. }
  24. return key;
  25. };
  26. const getTypeString = (value) => {
  27. if (value === null) {
  28. return 'null';
  29. }
  30. if (Array.isArray(value)) {
  31. if (value.length === 0) {
  32. return 'unknown[]';
  33. }
  34. const types = Array.from(new Set(value.map(getTypeString)));
  35. if (types.length > 1) {
  36. return `(${types.join(' | ')})[]`;
  37. }
  38. return `${types.at(0)}[]`;
  39. }
  40. switch (typeof value) {
  41. case 'object': {
  42. const entries = Object.entries(value);
  43. if (entries.length === 0) {
  44. return 'Record<string, unknown>';
  45. }
  46. return `{${entries.map(([k, v]) => `${escapeKey(k)}: ${getTypeString(v)}`).join(', ')}}`;
  47. }
  48. case 'function':
  49. return 'Function';
  50. default:
  51. return typeof value;
  52. }
  53. };
  54. unsafeWindow.getTypeString = getTypeString;
  55. unsafeWindow.printTypeString = (value) => {
  56. console.log(getTypeString(value));
  57. };
  58.  
  59. })();