- 0133技术站
- 联系QQ:18840023
- QQ交流群
- 微信公众号
JSX是一种嵌入式的类似XML的语法。 它可以被转换成合法的JavaScript,尽管转换的语义是依据不同的实现而定的。 JSX因React框架而流行,但是也被其它应用所使用。 TypeScript支持内嵌,类型检查和将JSX直接编译为JavaScript。
想要使用JSX必须做两件事:
.tsx
扩展名jsx
选项TypeScript具有三种JSX模式:preserve
,react
和react-native
。
这些模式只在代码生成阶段起作用 - 类型检查并不受影响。
在preserve
模式下生成代码中会保留JSX以供后续的转换操作使用(比如:Babel)。
另外,输出文件会带有.jsx
扩展名。react
模式会生成React.createElement
,在使用前不需要再进行转换操作了,输出文件的扩展名为.js
。react-native
相当于preserve
,它也保留了所有的JSX,但是输出文件的扩展名是.js
。
模式 | 输入 | 输出 | 输出文件扩展名 |
---|---|---|---|
preserve | <div /> | <div /> | .jsx |
react | <div /> | React.createElement("div") | .js |
react-native | <div /> | <div /> | .js |
你可以通过在命令行里使用--jsx
标记或tsconfig.json里的选项来指定模式。
注意:
React
标识符是写死的硬编码,所以你必须保证React(大写的R)是可用的。
as
操作符回想一下怎么写类型断言:
var foo = <foo>bar;
这里我们断言bar
变量是foo
类型的。
因为TypeScript也使用尖括号来表示类型断言,JSX的语法带来了解析的困难。因此,TypeScript在.tsx
文件里禁用了使用尖括号的类型断言。
为了弥补.tsx
里的这个功能,新加入了一个类型断言符号:as
。
上面的例子可以很容易地使用as
操作符改写:
var foo = bar as foo;
as
操作符在.ts
和.tsx
里都可用,并且与其它类型断言行为是等价的。
为了理解JSX的类型检查,你必须首先理解固有元素与基于值的元素之间的区别。
假设有这样一个JSX表达式<expr />
,expr
可能引用环境自带的某些东西(比如,在DOM环境里的div
或span
)或者是你自定义的组件。
这是非常重要的,原因有如下两点:
React.createElement("div")
),然而由你自定义的组件却不会生成(React.createElement(MyComponent)
)。TypeScript使用与React相同的规范 来区别它们。 固有元素总是以一个小写字母开头,基于值的元素总是以一个大写字母开头。
固有元素使用特殊的接口JSX.IntrinsicElements
来查找。
默认地,如果这个接口没有指定,会全部通过,不对固有元素进行类型检查。
然而,如果这个接口存在,那么固有元素的名字需要在JSX.IntrinsicElements
接口的属性里查找。
例如:
declare namespace JSX { interface IntrinsicElements { foo: any } }<foo />; // 正确 <bar />; // 错误
在上例中,<foo />
没有问题,但是<bar />
会报错,因为它没在JSX.IntrinsicElements
里指定。
注意:你也可以在
JSX.IntrinsicElements
上指定一个用来捕获所有字符串索引:declare namespace JSX { interface IntrinsicElements { [elemName: string]: any; } }
基于值的元素会简单的在它所在的作用域里按标识符查找。
import MyComponent from "./myComponent"; <MyComponent />; // 正确 <SomeOtherComponent />; // 错误
有两种方式可以定义基于值的元素:
由于这两种基于值的元素在JSX表达式里无法区分,因此我们首先会尝试将表达式做为无状态函数组件进行解析。如果解析成功,那么我们就完成了表达式到其声明的解析操作。如果按照无状态函数组件解析失败,那么我们会继续尝试以类组件的形式进行解析。如果依旧失败,那么将输出一个错误。
正如其名,组件被定义成JavaScript函数,它的第一个参数是props
对象。
我们强制它的返回值可以赋值给JSX.Element
。
interface FooProp { name: string; X: number; Y: number; } declare function AnotherComponent(prop: {name: string}); function ComponentFoo(prop: FooProp) { return <AnotherComponent name=prop.name />; } const Button = (prop: {value: string}, context: { color: string }) => <button>
由于无状态函数组件是简单的JavaScript函数,所以我们还可以利用函数重载。
interface ClickableProps { children: JSX.Element[] | JSX.Element } interface HomeProps extends ClickableProps { home: JSX.Element; } interface SideProps extends ClickableProps { side: JSX.Element | string; } function MainButton(prop: HomeProps): JSX.Element; function MainButton(prop: SideProps): JSX.Element { ... }
我们可以限制类组件的类型。 然而,为了这么做我们需要引入两个新的术语:元素类的类型和元素实例的类型。
现在有<Expr />
,元素类的类型为Expr
的类型。
所以在上面的例子里,如果MyComponent
是ES6的类,那么它的类类型就是这个类。
如果MyComponent
是个工厂函数,类类型为这个函数。
一旦建立起了类类型,实例类型就确定了,为类类型调用签名的返回值与构造签名的联合类型。 再次说明,在ES6类的情况下,实例类型为这个类的实例的类型,并且如果是工厂函数,实例类型为这个函数返回值类型。
class MyComponent { render() {} } // 使用构造签名 var myComponent = new MyComponent(); // 元素类的类型 => MyComponent // 元素实例的类型 => { render: () => void } function MyFactoryFunction() { return { render: () => { } } } // 使用调用签名 var myComponent = MyFactoryFunction(); // 元素类的类型 => FactoryFunction // 元素实例的类型 => { render: () => void }
元素的实例类型很有趣,因为它必须赋值给JSX.ElementClass
或抛出一个错误。
默认的JSX.ElementClass
为{}
,但是它可以被扩展用来限制JSX的类型以符合相应的接口。
declare namespace JSX { interface ElementClass { render: any; } } class MyComponent { render() {} } function MyFactoryFunction() { return { render: () => {} } } <MyComponent />; // 正确 <MyFactoryFunction />; // 正确 class NotAValidComponent {} function NotAValidFactoryFunction() { return {}; } <NotAValidComponent />; // 错误 <NotAValidFactoryFunction />; // 错误
属性类型检查的第一步是确定元素属性类型。 这在固有元素和基于值的元素之间稍有不同。
对于固有元素,这是JSX.IntrinsicElements
属性的类型。
declare namespace JSX { interface IntrinsicElements { foo: { bar?: boolean } } } // `foo`的元素属性类型为`{bar?: boolean}` <foo bar />;
对于基于值的元素,就稍微复杂些。
它取决于先前确定的在元素实例类型上的某个属性的类型。
至于该使用哪个属性来确定类型取决于JSX.ElementAttributesProperty
。
它应该使用单一的属性来定义。
这个属性名之后会被使用。
declare namespace JSX { interface ElementAttributesProperty { props; // 指定用来使用的属性名 } } class MyComponent { // 在元素实例类型上指定属性 props: { foo?: string; } } // `MyComponent`的元素属性类型为`{foo?: string}` <MyComponent foo="bar" />
元素属性类型用于的JSX里进行属性的类型检查。 支持可选属性和必须属性。
declare namespace JSX { interface IntrinsicElements { foo: { requiredProp: string; optionalProp?: number } } } <foo requiredProp="bar" />; // 正确 <foo requiredProp="bar" optionalProp={0} />; // 正确 <foo />; // 错误, 缺少 requiredProp <foo requiredProp={0} />; // 错误, requiredProp 应该是字符串 <foo requiredProp="bar" unknownProp />; // 错误, unknownProp 不存在 <foo requiredProp="bar" some-unknown-prop />; // 正确, `some-unknown-prop`不是个合法的标识符
注意:如果一个属性名不是个合法的JS标识符(像
data-*
属性),并且它没出现在元素属性类型里时不会当做一个错误。
延展操作符也可以使用:
var props = { requiredProp: 'bar' }; <foo {...props} />; // 正确 var badProps = {}; <foo {...badProps} />; // 错误
从TypeScript 2.3开始,我们引入了children类型检查。children是元素属性(attribute)类型的一个属性(property)。
与使用JSX.ElementAttributesProperty
来决定props名类似,我们可以利用JSX.ElementChildrenAttribute
来决定children名。JSX.ElementChildrenAttribute
应该被声明在单一的属性(property)里。
declare namespace JSX { interface ElementChildrenAttribute { children: {}; // specify children name to use } }
如不特殊指定子孙的类型,我们将使用React typings里的默认类型。
<div> <h1>Hello</h1> </div>; <div> <h1>Hello</h1> World </div>; const CustomComp = (props) => <div>props.children</div> <CustomComp> <div>Hello World</div> {"This is just a JS expression..." + 1000} </CustomComp>
你也可以像其它属性一样指定children的类型。下面我们重写React typings里的默认类型。
interface PropsType { children: JSX.Element name: string } class Component extends React.Component<PropsType, {}> { render() { return ( <h2> this.props.children </h2> ) } } // OK <Component> <h1>Hello World</h1> </Component> // Error: children is of type JSX.Element not array of JSX.Element <Component> <h1>Hello World</h1> <h2>Hello World</h2> </Component> // Error: children is of type JSX.Element not array of JSX.Element or string. <Component> <h1>Hello</h1> World </Component>
默认地JSX表达式结果的类型为any
。
你可以自定义这个类型,通过指定JSX.Element
接口。
然而,不能够从接口里检索元素,属性或JSX的子元素的类型信息。
它是一个黑盒。
JSX允许你使用{ }
标签来内嵌表达式。
var a = <div> {['foo', 'bar'].map(i => <span>{i / 2}</span>)} </div>
上面的代码产生一个错误,因为你不能用数字来除以一个字符串。
输出如下,若你使用了preserve
选项:
var a = <div> {['foo', 'bar'].map(function (i) { return <span>{i / 2}</span>; })} </div>
要想一起使用JSX和React,你应该使用React类型定义。
这些类型声明定义了JSX
合适命名空间来使用React。
/// <reference path="react.d.ts" /> interface Props { foo: string; } class MyComponent extends React.Component<Props, {}> { render() { return <span>{this.props.foo}</span> } } <MyComponent foo="bar" />; // 正确 <MyComponent foo={0} />; // 错误
推荐手册