|
| 1 | +class TypeChecker { |
| 2 | + static matchType(value, expected) { |
| 3 | + if (Array.isArray(expected)) return expected.some((e) => this.checkType(value, e)); |
| 4 | + return this.checkType(value, expected); |
| 5 | + } |
| 6 | + |
| 7 | + static checkType(value, expected) { |
| 8 | + if (expected === null) return value === null; |
| 9 | + if (expected === undefined) return value === undefined; |
| 10 | + if (expected === String || expected === Number || expected === Boolean || expected === Symbol || expected === Function || expected === BigInt) return typeof value === expected.name.toLowerCase(); |
| 11 | + if (expected === Object) return typeof value === "object" && value !== null && !Array.isArray(value); |
| 12 | + if (expected === Array) return Array.isArray(value); |
| 13 | + // ----- DynamicEnum対応 |
| 14 | + if (expected instanceof _DynamicEnumCore) { |
| 15 | + // DynamicEnumの場合 |
| 16 | + return expected.has(value?.name); |
| 17 | + } |
| 18 | + if (expected === _EnumItem) return value instanceof _EnumItem; |
| 19 | + // ----- |
| 20 | + if (typeof expected === "function") return value instanceof expected; |
| 21 | + return false; |
| 22 | + } |
| 23 | + |
| 24 | + static typeNames(expected) { |
| 25 | + if (Array.isArray(expected)) return expected.map((t) => t?.name || TypeChecker.__iface_stringify(t)).join(" | "); |
| 26 | + return expected?.name || TypeChecker.__iface_stringify(expected); |
| 27 | + } |
| 28 | + |
| 29 | + static stringify(value) { |
| 30 | + if (value === null || value === undefined) { |
| 31 | + return String(value); |
| 32 | + } |
| 33 | + if (typeof value === "object") { |
| 34 | + if (value?.toString() !== "[object Object]") { |
| 35 | + return String(value); |
| 36 | + } |
| 37 | + try { |
| 38 | + const jsonString = JSON.stringify( |
| 39 | + value, |
| 40 | + (key, val) => { |
| 41 | + if (val && typeof val === "object") { |
| 42 | + const size = Object.keys(val).length; |
| 43 | + // オブジェクトが大きすぎる場合は省略表示 |
| 44 | + if (size > 5) { |
| 45 | + return `Object with ${size} properties`; |
| 46 | + } |
| 47 | + } |
| 48 | + return val; |
| 49 | + }, |
| 50 | + 0 |
| 51 | + ); |
| 52 | + // JSON.stringifyエラー時にfallback |
| 53 | + if (jsonString === undefined) { |
| 54 | + return "Object is too large to display or contains circular references"; |
| 55 | + } |
| 56 | + |
| 57 | + return jsonString.length > 1000 ? "Object is too large to display" : jsonString; // 文字数が多すぎる場合は省略 |
| 58 | + } catch (e) { |
| 59 | + return `[オブジェクト表示エラー: ${e.message}]`; // サークル参照等のエラー防止 |
| 60 | + } |
| 61 | + } |
| 62 | + return String(value); // それ以外の型はそのまま文字列に変換 |
| 63 | + } |
| 64 | +} |
0 commit comments