作者:邪恶尽头是纯洁 | 来源:互联网 | 2023-09-13 13:19
获取数据类型的三种方式1.typeofconsole.log(typeof1);numberconsole.log(typeoftrue);booleanconsole.l
获取数据类型的三种方式 1. typeof console. log ( typeof 1 ) ; console. log ( typeof true ) ; console. log ( typeof 'mc' ) ; console. log ( typeof Symbol) console. log ( typeof function ( ) { } ) ; console. log ( typeof console. log ( ) ) ; console. log ( typeof [ ] ) ; console. log ( typeof { } ) ; console. log ( typeof null ) ; console. log ( typeof undefined ) ;
优点:能够快速区分基本数据类型
缺点:不能将Object、Array和Null区分,都返回object
2.instanceof console. log ( 1 instanceof Number ) ; console. log ( true instanceof Boolean ) ; console. log ( 'str' instanceof String ) ; console. log ( [ ] instanceof Array ) ; console. log ( function ( ) { } instanceof Function ) ; console. log ( { } instanceof Object ) ;
优点:能够区分Array、Object和Function,适合用于判断自定义的类实例对象
缺点:Number,Boolean,String基本数据类型不能判断
3.Object.prototype.toString.call() var toString = Object . prototype. toString; console. log ( toString . call ( 1 ) ) ; console. log ( toString . call ( true ) ) ; console. log ( toString . call ( 'mc' ) ) ; console. log ( toString . call ( [ ] ) ) ; console. log ( toString . call ( { } ) ) ; console. log ( toString . call ( function ( ) { } ) ) ; console. log ( toString . call ( undefined ) ) ; console. log ( toString . call ( null ) ) ;
优点:精准判断数据类型
缺点:写法繁琐不容易记,推荐进行封装后使用
typeScript小结 any和unknown区别 任何属性都可以赋值unknow,unknow属性只能赋值unknown和any属性
is 类型谓词 const func = ( str: any) : boolean => { return typeof str === 'string' ; } ; const test = ( foo : any) => { if ( func ( foo) ) { console. log ( foo. length) ; console. log ( foo. toExponential ( 2 ) ) ; } } ; test ( 'string' )
当设置func返回值为布尔型时,运行时报错 TypeError: foo.toExponential is not a function ,原因是因为string类型并没有toExponential方法,但是这种情况可以在编译时就可以发现问题并且规避,这是就需要用到我们的is 类型谓词,代码如下
const func = ( str: any) : str is string => { return typeof str === 'string' ; } ; const test = ( foo : any) => { if ( func ( foo) ) { console. log ( foo. length) ; console. log ( foo. toExponential ( 2 ) ) ; } } ;
通过is 类型谓词,缩小变量的类型,类型保护的作用域仅仅在 if 后的块级作用域中生效,在if块级作用域下foo变量从any进一步约束为string类型,从而能够在编译时直接发现错误