3 回答
TA贡献1883条经验 获得超3个赞
你不会找到一个正确的答案,但你可以找到强烈的意见。我的观点是:它各不相同。以下是我的库中的一些类型检查
const isDefined = x => x !== undefined && x !== null
const isUndefined = x => x === undefined
const isNull = x => x === null
const isIterable = x => isDefined(x) && isDefined(x[Symbol.iterator])
const isAsyncIterable = x => isDefined(x) && isDefined(x[Symbol.asyncIterator])
const isReadable = x => x && typeof x.read === 'function'
const isWritable = x => x && typeof x.write === 'function'
const isFunction = x => typeof x === 'function'
const isArray = Array.isArray
const numberTypedArrays = new Set([
'Uint8ClampedArray',
'Uint8Array', 'Int8Array',
'Uint16Array', 'Int16Array',
'Uint32Array', 'Int32Array',
'Float32Array', 'Float64Array',
])
const isNumberTypedArray = x => x && x.constructor && (
numberTypedArrays.has(x.constructor.name)
)
const bigIntTypedArrays = new Set([
'BigUint64Array', 'BigInt64Array',
])
const isBigIntTypedArray = x => x && x.constructor && (
bigIntTypedArrays.has(x.constructor.name)
)
const isNumber = x => typeof x === 'number'
const isBigInt = x => typeof x === 'bigint'
const isString = x => typeof x === 'string'
const isPromise = x => x && typeof x.then === 'function'
const is = fn => x => x && x.constructor === fn
const isObject = is(Object) // checks directly for Object, isObject([]) === false
如果您正在寻找一种快速方法来检查给定构造函数的类型,我建议复制和粘贴并使用它,以便is
const is = fn => x => x && x.constructor === fn
exampleFunction1(a,b){
if(is(Number)(a) && is(Number)(b)){
return a+b;
}else{
console.log('%cType Error : exampleFunction1(<Number>)','color:#00FF66;')
}
}
打字就更少了。
TA贡献1812条经验 获得超5个赞
您应该使用方法检查是否为数字isNaN
addNumbers(a,b){
if(
!isNaN(a) &&
!isNaN(b)
){
return a+b;
}else{
console.log('%cType Error : findUniqueInArray(<Array>)','color:#00FF66;')
}
}
TA贡献1854条经验 获得超8个赞
依赖似乎不是最安全的选择,因为任何对象都可以实现自己的.toString()toString()
我会去:Number.isFinite()
if (Number.isFinite(a) && Number.isFinite(b)) {
如果您只想检查类型,则有一个运算符:typeof
typeof 1 // "number"
typeof 'a' // "string"
typeof {} // "object"
至于,库经常实现自己的来帮助你调试。以下是使用类完成操作的方式:toString()toString()
class Foo {
toString() {
return 'I am mr. Foo';
}
}
const bar = new Foo();
bar.toString() // "I am mr. Foo"
添加回答
举报