Detect Types

Register a function to generate runtime window type definitions.

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name            Detect Types
// @namespace       https://github.com/SlashNephy
// @version         0.1.0
// @author          SlashNephy
// @description     Register a function to generate runtime window type definitions.
// @description:ja  window の型定義を生成する関数を登録します。
// @homepage        https://scrapbox.io/slashnephy
// @homepageURL     https://scrapbox.io/slashnephy
// @icon            https://www.google.com/s2/favicons?sz=64&domain=*
// @supportURL      https://github.com/SlashNephy/userscripts/issues
// @match           https://*/*
// @grant           unsafeWindow
// @license         MIT license
// ==/UserScript==

(function () {
    'use strict';

    const escapeKey = (key) => {
        if (key.includes('.')) {
            return `'${key}'`;
        }
        return key;
    };
    const getTypeString = (value) => {
        if (value === null) {
            return 'null';
        }
        if (Array.isArray(value)) {
            if (value.length === 0) {
                return 'unknown[]';
            }
            const types = Array.from(new Set(value.map(getTypeString)));
            if (types.length > 1) {
                return `(${types.join(' | ')})[]`;
            }
            return `${types.at(0)}[]`;
        }
        switch (typeof value) {
            case 'object': {
                const entries = Object.entries(value);
                if (entries.length === 0) {
                    return 'Record<string, unknown>';
                }
                return `{${entries.map(([k, v]) => `${escapeKey(k)}: ${getTypeString(v)}`).join(', ')}}`;
            }
            case 'function':
                return 'Function';
            default:
                return typeof value;
        }
    };
    unsafeWindow.getTypeString = getTypeString;
    unsafeWindow.printTypeString = (value) => {
        console.log(getTypeString(value));
    };

})();