|
typescript 中常见的公用方法封装:
hasOwn: 判断val是否含有属性key;
const hasOwnProperty = Object.prototype.hasOwnProperty
export const hasOwn = (
val: object,
key: string | symbol
): key is keyof typeof val => hasOwnProperty.call(val, key)
复制代码
isArray:判断是否为数组;
export const isArray = Array.isArray
复制代码
isFunction: 判断是否为函数
export const isFunction = (val: unknown): val is Function =>
typeof val === 'function'
复制代码
isString:判断是否为字符串
export const isString = (val: unknown): val is string => typeof val === 'string'
复制代码
isSymbol:判断是否为symbol
export const isSymbol = (val: unknown): val is symbol => typeof val === 'symbol'
复制代码
isObject:判断是否为object
export const isObject = (val: unknown): val is Record<any, any> =>
val !== null && typeof val === 'object'
复制代码
isPromise:判断是否为promise
export function isPromise<T = any>(val: unknown): val is Promise<T> {
return isObject(val) && isFunction(val.then) && isFunction(val.catch)
}
复制代码
isPlainObject:判断是否为plainObject
export const objectToString = Object.prototype.toString
export const toTypeString = (value: unknown): string =>
objectToString.call(value)
export const isPlainObject = (val: unknown): val is object =>
toTypeString(val) === '[object Object]'
|
|