zoukankan      html  css  js  c++  java
  • [TypeScript] Use TypeScript’s never Type for Exhaustiveness Checking

    TypeScript 2.0 introduced a new primitive type called never, the type of values that never occur. It helps model the completion behavior of functions more accurately and can also be used for exhaustiveness checking.

    never type means that 'That part of code cannot be reached'.

    In somecases, never type can be useful as well.

    const enum ShirtSize {
      XS,
      S,
      M,
      L,
      XL
    }
    
    function assertNever(value: never): never {
      // throw Error(`Unexpected value '${value}'`)
      // Adjusted for plunker output
      console.log(Error(`Unexpected value '${value}'`));
    }
    
    function prettyPrint(size: ShirtSize) {
      switch (size) {
          case ShirtSize.S: console.log("small");
          case ShirtSize.M: return "medium";
          case ShirtSize.L: return "large";
          case ShirtSize.XL: return "extra large";
          // [ts] Argument of type 'ShirtSize.XS' is
          // not assignable to parameter of type 'never'.
          default: return assertNever(size);
      }
    }
    
    prettyPrint(ShirtSize.S)
    prettyPrint(ShirtSize.XXL)

    In the example, we want to make sure that every time in the enum ShirtSzie has been handled by the 'prettyPrint' function.

    But sometime, we might miss one case. That's where 'assertNever' function can help to make sure, we have gone though all the cases.

  • 相关阅读:
    谢尔宾斯基三角形,“混沌游戏”实现 20141022
    Who are you, What is the science
    The Tao to Excellent 2
    Mac Mini Server安装Centos6.5
    关于ftp的功能类——下载,上传,断点,连接
    mysql http://yaojialing.iteye.com/blog/773973
    序列号
    JS 文件复制
    java MySQLFront_Setup
    牛人博客
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7811540.html
Copyright © 2011-2022 走看看