Advertisement

08-TypeScript-中-is-关键字

阅读量:

TypeScript 中 is 关键字

此乃个人学习总结也。原文地址:TypeScript 中的 is

TypeScript 里有类型的保护机制。要实现一种类型保护功能,则只需编写一个函数,其返回值为一种判断逻辑

复制代码
    function isString(test: any): test is string {
      return typeof test === 'string'
    }

上述写法与写一个返回值为 boolean 值函数的区别在哪里呢?

复制代码
    function isString(test: any): boolean {
      return typeof test === 'string'
    }

使用 is 类型保护

复制代码
    function isString(test: any): test is string {
      return typeof test === 'string'
    }
    
    function example(foo: any) {
      if (isString(foo)) {
    console.log('it is a string' + foo)
    console.log(foo.length) // string function
    // 如下代码编译时会出错,运行时也会出错,因为 foo 是 string 不存在 toExponential 方法
    console.log(foo.toExponential(2))
      }
      // 编译不会出错,但是运行时出错
      console.log(foo.toExponential(2))
    }
    example('hello world')

返回值为 boolean

复制代码
    function isString(test: any): boolean {
      return typeof test === 'string'
    }
    
    function example(foo: any) {
      if (isString(foo)) {
    console.log('it is a string' + foo)
    console.log(foo.length) // string function
    // foo 为 any,编译正常。但是运行时会出错,因为 foo 是 string 不存在 toExponential 方法
    console.log(foo.toExponential(2))
      }
    }
    example('hello world')

总结

  • 当采用类型保护策略时,在TS中会更严格地限制变量的数据范围。例如,在示例中,默认情况下的任何值会被限定为string类型的值;
    • 通过这种机制,在if语句之后的代码块内,默认参数会被强制指定数据类型。

原文引自:金点网络/数媒派 作者:jamin

全部评论 (0)

还没有任何评论哟~