抽象一个类型判断库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
export function type(x) {
const t = typeof x
if (x === null) {
return 'null'
}
if (t !== 'object') {
return t
}
const toString = Object.prototype.toString
const innerType = toString.call(x).slice(8, -1)
const innerLowType = innerType.toLowerCase()

if (['String', 'Boolean', 'Number'].includes(innerType)) {
return innerType
}

if (typeof x?.constructor?.name === 'string') {
return x.constructor.name
}

return innerLowType
}