本文介绍了TypeScript中尖括号的使用规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

决定何时、何地、如何以及为什么在 TypeScript 中使用尖括号(即 <...>)的一般规则是什么?

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

虽然我认为我理解这些括号的许多单独用法,但我很难看到它们的一般使用模式:它们有时似乎放在事物之前,有时附加在事物之后;有时它们用于泛型,有时用于特定类型;有时它们会出现在我可能期望使用冒号语法的地方.

While I think I understand many individual uses of these brackets, I have a hard time seeing general patterns for their use: they sometimes seem to be prepended before things, sometimes appended after things; sometimes they are used for generics, sometimes for specific types; sometimes they appear where I might have expected the colon syntax to be used.

我想对括号的含义、它们的确切语法、何时应该使用、何时不应该使用等进行简洁但详尽/通用的解释.

I'd like to have a concise but exhaustive/universal explanation of what the brackets mean, their exact syntax, when they should be used, when they shouldn't be used, etc.

推荐答案

对于这样的问题,我建议阅读 规范,尤其是语法部分.像 < 这样的语法

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

  1. 类型参数

  • 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

类型参数

  • 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

2018-07-01 更新:从 2.9 版开始,泛型类型参数也可以用于 JSX 元素标记模板.

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

类型断言

var ingredients = {
    toppingA: new Pepperoni,
    toppingB: <Mozzarella> fridge.takeSomeCheese()
            //^^^^^^^^^^^^ Type assertion
};

JSX 表达式(启用时)

  • 未在规范中记录,但应遵循 JSX 的语法,这基本上是一个表达式,如

  • 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>

<JSXElementName JSXAttributes(optional) />

这篇关于TypeScript中尖括号的使用规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-25 15:29
查看更多