Skip to content
On this page

getType获取类型

Hidden Title

基础用法:getType(value)

基础用法

说明

getType 用于获取值的原始类型名称,并统一返回小写字符串。相比直接使用 typeof,它能区分 arraydateregexpmapweakmapnull 等对象类型。

调用形式

ts
getType(value)
getType(value)

参数说明

参数类型必填默认值说明
valueunknown-要判断类型的任意值。

返回值

返回小写类型字符串。基础类型返回 typeof 结果,对象类型返回 Object.prototype.toString 解析出的类型。

常见返回值:

输入返回值
123'number'
'text''string'
null'null'
undefined'undefined'
[]'array'
{}'object'
new Date()'date'
/abc/'regexp'
new Map()'map'
new WeakMap()'weakmap'

常用场景

ts
getType([])
// 'array'

getType(null)
// 'null'

getType(new RegExp('abc'))
// 'regexp'
getType([])
// 'array'

getType(null)
// 'null'

getType(new RegExp('abc'))
// 'regexp'

注意事项

getType 只返回类型名称,不做类型收窄。如果在 TypeScript 中需要类型保护,可以结合 packages/utils/src/is.ts 中的 isArrayisMapisFunction 等方法。

函数源码

getType

来源:packages/utils/src/base.ts

/**
 * 获取值的原始类型名称,返回值统一为小写字符串。
 *
 * @param type 要判断的值。
 * @returns 类型名称,例如 `array`、`date`、`object`、`null`。
 *
 * @example
 * getType(new RegExp())
 * // => 'regexp'
 *
 * @example
 * getType([])
 * // => 'array'
 */
export function getType(type: unknown): string {
  if (typeof type === 'object') {
    const objType = Object.prototype.toString.call(type).slice(8, -1).toLowerCase()
    return objType
  } else {
    return typeof type
  }
}

思云博智私有前端组件库