Rules for the use of angle brackets in Typescript

后端 未结 2 1358
太阳男子
太阳男子 2020-12-02 10:48

What are the general rules that dictate when, where, how and why angle brackets, i.e. \"<...>\", should be used in TypeScript?

Wh

2条回答
  •  渐次进展
    2020-12-02 11:33

    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(food: T): T { return food; }
                  //^^^^^ Type parameter list
        
        class Pizza { 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;
                       //^^^^^^^^^^^^^^^^^^^^^^ 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.

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

      • Defined and used as < Type > UnaryExpression where UnaryExpression comes from EcmaScript standard in section 4.16

        var ingredients = {
            toppingA: new Pepperoni,
            toppingB:  fridge.takeSomeCheese()
                    //^^^^^^^^^^^^ Type assertion
        };
        
    4. JSX expressions (when enabled)

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

         JSXChildren(optional) 
        

        or

        
        

提交回复
热议问题