Why are typeguards using toString instead of typeof?
nexxeln opened this issue · 2 comments
nexxeln commented
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;
}
kfirfitousi commented
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]"
LuciNyan commented
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?