问题描述
决定何时、何地、如何以及为什么在 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
类型参数
定义为<部分中的TypeParameterList >
3.6.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
类型参数
- 定义为<中的TypeArgumentList >3.6.2
与泛型类型的引用和泛型函数的调用一起使用
- 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
类型断言
定义并用作
UnaryExpression
其中 UnaryExpression 来自 EcmaScript 标准 在 第 4.16 节 中
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中尖括号的使用规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!