Rules for the use of angle brackets in Typescript

雨燕双飞 提交于 2019-11-29 21:00:28

With questions like this, I'd recommend reading the spec, especially the Grammar section. Syntax like < something > is used in

  1. Type Parameters

    • Defined as < TypeParameterList > in section 3.6.1
    • Used with declarations and call signatures of classes, interfaces, functions and more

      function heat<T>(food: T): T { return food; }
                //^^^^^ Type parameter list
      
      class Pizza<T, E extends Cheese> { toppingA: T; toppingB: E }
               //^^^^^^^^^^^^^^^^^^^^ Type parameter list
      
  2. Type Arguments

    • Defined as < TypeArgumentList > in section 3.6.2
    • Used with references to generic types and calls to generic functions

      var pizza: Pizza<Pepperoni, Mozzarella>;
                     //^^^^^^^^^^^^^^^^^^^^^^ Type argument list
      pizza = heat<{ toppingA: Pepperoni, toppingB: Mozzarella}>(ingredients) 
                 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Type argument list
      

      Update 2018-07-01: As of version 2.9, generic type arguments can also be used in JSX elements and tagged templates.

       <MenuItem<Pizza> toppings={[Pepperoni, Mozzarella]} />
              //^^^^^^^ Type argument list
      
       const ratingHtml = escapeUserInput<string | number> `Customer ${feedback.customer.username} rated this pizza with <b>${feedback.rating}</b>/10!`
                                        //^^^^^^^^^^^^^^^^ Type argument list
      
  3. Type Assertions

  4. JSX expressions (when enabled)

    • Not documented in the spec, but should follow the the syntax of JSX, which is basically an expression like

      <JSXElementName JSXAttributes(optional)> JSXChildren(optional) </JSXElementName>
      

      or

      <JSXElementName JSXAttributes(optional) />
      

They are used for multiple, far too semantically distinct expressions for one to formulate a common use case over them. It also depends on context, much like curly brackets. As you probably know, angle brackets in pairs are used:

  • As a deprecated syntax for type-assertions
  • For manually specifying generic type parameters
  • For declaring elements in .tsx

When not in a .tsx file, angle brackets in pairs are virtually always the indication of the presence of a generic type parameter. One might formulate a system of expressions as such (which is probably the closest you can get):

  • When in the context of a type definition, type annotation, method invocation, or class declaration, angle brackets denote a generic type parameter
  • When in the context of a TSX element, angle brackets denote an element as transpiled by a TSX/JSX compiler
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!