LuciNyan / ts-known

This library offers guards for common types, and methods to generate type guards for specific types quickly. Safely handle unpredictable unknown types with ease.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why are typeguards using toString instead of typeof?

nexxeln opened this issue · comments

What is the reason to use the toString function and then check the output instead of using typeof?

// current implementation
export function isObject(x: unknown): x is object {
  return toString(x) === '[object Object]'
}

// with typeof
export function isObject(x: unknown): x is object {
  return typeof x === "object" && x !== null;
}

toString gives more information than typeof.

typeof new Date // "object"
toString(new Date) // "[object Date]"

typeof null // "object" (WHY JAVASCRIPT? WHY??)
toString(null) // "[object Null]"

Hi @nexxeln! Thank you for raising this interesting question! I have the same opinion as @kfirfitousi. And I wonder if we could change the return type of isObject to x is Record<PropertyKey, unknown>. This could make it more meaningful. What do you think?

image