Last active
May 29, 2025 18:37
-
-
Save wzulfikar/ce42ba0c63e2d3ffc04a98531d41ca3f to your computer and use it in GitHub Desktop.
type-of.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type BetterTypeof<T> = | |
T extends number | |
? "number" | "integer" | "NaN" | |
: T extends string | |
? "string" | |
: T extends boolean | |
? "boolean" | |
: T extends undefined | |
? "undefined" | |
: T extends null | |
? "null" | |
: T extends readonly any[] | |
? "array" | |
: T extends Date | |
? "Date" | |
: T extends Set<any> | |
? "Set" | |
: T extends Map<any, any> | |
? "Map" | |
: T extends object | |
? "object" | |
: "unknown"; | |
export const typeOf = <T,>(data: T): BetterTypeof<T> => { | |
const t = typeof data; | |
if (t === "number") { | |
if (Number.isNaN(data)) return "NaN" as BetterTypeof<T>; | |
if (Number.isInteger(data)) return "integer" as BetterTypeof<T>; | |
return "number" as BetterTypeof<T>; | |
} | |
if (t === "object") { | |
if (Array.isArray(data)) return "array" as BetterTypeof<T>; | |
if (data === null) return "null" as BetterTypeof<T>; | |
if (data && Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { | |
return data.constructor.name as BetterTypeof<T>; // "Date", "Set", etc | |
} | |
return "object" as BetterTypeof<T>; | |
} | |
return t as BetterTypeof<T>; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { typeOf } from "./type-of" | |
const b = typeOf({ user: 1 }) | |
// ^? "object" | |
const someNumber = typeOf(1) | |
// ^? "number" | "integer" | "NaN" | |
const someString = typeOf("1") | |
// ^? "string" | |
const someBoolean = typeOf(true) | |
// ^? "boolean" | |
const someUndefined = typeOf(undefined) | |
// ^? "undefined" | |
const someNull = typeOf(null) | |
// ^? "null" | |
const someArray = typeOf([1, 2, 3]) | |
// ^? "array" | |
const someDate = typeOf(new Date()) | |
// ^? "Date" | |
const someSet = typeOf(new Set([1, 2, 3])) | |
// ^? "Set" | |
const someMap = typeOf(new Map([["a", 1], ["b", 2]])) | |
// ^? "Map" | |
if (typeOf(1) === "number") { | |
console.log("1 is a number") | |
} | |
if (typeOf(1) === "string") { | |
// type check error because "number" and "string" are not compatible | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by @colinhacks's post and other comments. Original post: https://x.com/colinhacks/status/1927640989696688277