网络科技

    今日:7| 主题:301288
收藏本版
互联网、科技极客的综合动态。

[其他] TypeScript 2.0: Control Flow Based Type Analysis

[复制链接]
叫兽都走了 发表于 2016-10-1 07:26:10
129 3
The    recent releaseof TypeScript 2.0 shipped with plenty of new features. I previously wrote about the newnon-nullable types, which go hand in hand with another feature we're going to look at in this post: type analysis based on control flow.  
  Control Flow Based Type Analysis

  The official    What's new in TypeScriptpage summarizes control flow based type analysis as follows (emphasis mine):  
  With TypeScript 2.0, the type checker analyses all possible flows of control in statements and expressions to produce    the most specific type possible(the    narrowed type)    at any given locationfor a local variable or parameter that is declared to have a union type.  
  That's a pretty dense explanation. Here's an example that illustrates how TypeScript understands the effect of assignments to a local variable, and how it    narrowsthe type of that variable accordingly:  
  1. let command: string | string[];

  2. command = "pwd";
  3. command.toLowerCase();    // Here, command is of type 'string'

  4. command = ["ls", "-la"];
  5. command.join(" ");        // Here, command is of type 'string[]'
复制代码
Note that all code resides within the same scope. Still, the type checker uses the most specific type possible for the    commandvariable at any given location:  
  
       
  • After the string      "pwd"has been assigned, there's no way for the      commandvariable to be a string array (the only other option within the union type). Therefore, TypeScript treats      commandas a variable of type      stringand allows the call to the      toLowerCase()method.   
  • After the string array      ["ls", "-la"]is assigned, the      commandvariable is no longer treated as a string. It is now known to be a string array, so the call to the      joinmethod succeeds.  
  Because of the same control flow analysis, the following function type-checks correctly in TypeScript 2.0:
  1. function composeCommand(command: string | string[]): string {
  2.     if (typeof command === "string") {
  3.         return command;
  4.     }

  5.     return command.join(" ");
  6. }
复制代码
The compiler now understands that if the    commandparameter is of type    string, the function always returns early from within the    if-statement. Because of the early exit behavior, the type of the    commandparameter is narrowed to    string[]after the    if-statement. As a result, the call to the    joinmethod type-checks correctly.  
  Prior to TypeScript 2.0, the compiler was not able to deduce the above semantics. Therefore, the    stringtype was not removed from the union type of the    commandvariable, and the following compile-time error was produced:  
  1. Property 'join' does not exist on type 'string | string[]'.
复制代码
Strict Null Checks

  Control flow based type analysis is particularly helpful when used in conjunction with nullable types, which are represented using union types including    nullor    undefined. Usually, we need to check whether a variable of a nullable type has a non-null value before we can work with it:  
  1. type Person = {
  2.     firstName: string;
  3.     lastName?: string | null | undefined;
  4. };

  5. function getFullName(person: Person): string {
  6.     const { firstName, lastName } = person;

  7.     // Here, we check for a falsy value of the `lastName` property,
  8.     // which covers `null` and `undefined` (and other values like "")
  9.     if (!lastName) {
  10.         return firstName;
  11.     }

  12.     return `${firstName} ${lastName}`;
  13. }
复制代码
Here, the    Persontype defines a non-nullable    firstNameproperty and a nullable    lastNameproperty. If we compose a full name out of both, we need to check whether    lastNameis    nullor    undefinedto avoid appending the string    "null"or    "undefined"to the first name.  
  For the purpose of clarity, I added the    undefinedtype to the union type of the    lastNameproperty, although that's a redundant piece of information. In strict null checking mode, the    undefinedtype is added automatically to the union type of optional properties, so we don't have to explicitly write it out. For more information, please refer to my previous post aboutnon-nullable types.  
  Definite Assignment Analysis

  Another new feature built on top of control flow is    definite assignment analysis. In strict null checking mode, local variables cannot be referenced before they have been assigned:  
  1. let name: string;

  2. // Error: Variable 'name' is used before being assigned.
  3. console.log(name);
复制代码
An exception to this rule are local variables whose type includes    undefined:  
  1. let name: string | undefined;
  2. console.log(name);  // No error
复制代码
Definite assignment analysis is another protection measure against nullability bugs. The idea is to make sure that every non-nullable local variable has been initialized properly before it's being used.
  Summary

  Control flow based type analysis is a powerful addition to TypeScript's type system. The type checker now understands the semantics of assignments and jumps in control flow, thereby greatly reducing the need for type guards. Working with nullable variables can be facilitated by the elimination of the    nulland    undefinedtypes. Finally, control flow analysis prevents referencing variables that have not definitely been assigned at the given location.
xxd4527 发表于 2016-10-1 07:33:49
男人嘴巴眯眯甜心都一把苣苣莲!
回复 支持 反对

使用道具 举报

506657718 发表于 2016-10-1 16:59:21
我来一个充满激情的回复
回复 支持 反对

使用道具 举报

问薇 发表于 2016-10-2 12:00:32
美女未抱身先走,常使色狼泪满襟。。。。。。  
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表