• TS 3.1


    总结

    • 元素分为固有元素(例如<div>)和基于值的元素,基于值的元素又分为无状态函数组件 (SFC)和类组件
    • 元素实例的类型是构造函数的实例类型或工厂函数(声明式函数function(){}而非表达式()=>{})的返回类型,两者的实例类型都受限于 JSX.ElementClass。vue 中类组件返回的是实例类型继承于 Vue,即 JSX.ElementClass extends Vue。
    • 元素的结果类型受限于 JSX.Element。vue 要求 JSX 元素的结果类型要满足 VNode,即 JSX.Element extends VNode;元素的结果类型是值该元素在 jsx 中时返回的类型
    // 该写法满足了元素实例类型的要求,但是没法满足结果类型的限制所以在 vue 中不适用
    function FunctionalComponent(){
         return {
            functional: true,
            props: {},
            render(h, ctx) {}               
         }
    }
    // 函数表达式不需要受函数实例类型的限制,配合 babel 插件可以写为,就可以满足元素结果类型的限定
    const FunctionalComponent= (ctx) => { return <div></div> }
    
    • 固有元素的属性类型由 JSX.IntrinsicElements 内定义
    • 基于值的元素的属性类型可以由 JSX.ElementAttributesProperty 指定实例类型中的某个属性的类型,如果未指定那么将使用类元素构造函数或 SFC(无状态函数组件) 调用的第一个参数的类型。(vue 不适用)
    • 元素的属性类型也可以是 JSX.LibraryManagedAttributes 这个泛型的返回值
    • JSX.LibraryManagedAttributes<Constructor,Params>其中 Constructor 为类的构造函数类型或工厂函数的类型,Params 为函数第一个参数的类型。
    • JSX.IntrinsicAttributesJSX.IntrinsicClassAttributes<T>可以用来为固有元素和基于值元素扩展额外的属性类型,例如 vue 中的 key、ref 等。vue 不需要因为已经用 LibraryManagedAttributes 泛型扩展了属性类型。
    • JSX.ElementChildrenAttribute用于设置当前组件插槽类型的类型来源。vue不需要,所有插槽归入作用域插槽中。
    • tsconfig 中 jsxFactory 用于配置 JSX 类型检查的命名空间,vue-tsx-support 需要配置该项。

    原文地址 www.tslang.cn

    介绍

    JSX 是一种嵌入式的类似 XML 的语法。 它可以被转换成合法的 JavaScript,尽管转换的语义是依据不同的实现而定的。 JSX 因 React 框架而流行,但也存在其它的实现。 TypeScript 支持内嵌,类型检查以及将 JSX 直接编译为 JavaScript。

    基本用法

    想要使用 JSX 必须做两件事:

    1. 给文件一个.tsx扩展名
    2. 启用jsx选项

    TypeScript 具有三种 JSX 模式:preservereactreact-native。 这些模式只在代码生成阶段起作用 - 类型检查并不受影响。 在preserve模式下生成代码中会保留 JSX 以供后续的转换操作使用(比如:Babel)。 另外,输出文件会带有.jsx扩展名。 react模式会生成React.createElement,在使用前不需要再进行转换操作了,输出文件的扩展名为.jsreact-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)是可用的。

    类型检查

    为了理解 JSX 的类型检查,你必须首先理解固有元素与基于值的元素之间的区别。 假设有这样一个 JSX 表达式<expr />expr可能引用环境自带的某些东西(比如,在 DOM 环境里的divspan)或者是你自定义的组件。 这是非常重要的,原因有如下两点:

    1. 对于 React,固有元素会生成字符串(React.createElement("div")),然而由你自定义的组件却不会生成(React.createElement(MyComponent))。
    2. 传入 JSX 元素里的属性类型的查找方式不同。 固有元素属性_本身_就支持,然而自定义的组件会自己去指定它们具有哪个属性。

    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 />; // 错误
    

    有两种方式可以定义基于值的元素:

    1. 无状态函数组件 (SFC)
    2. 类组件

    由于这两种基于值的元素在 JSX 表达式里无法区分,因此 TypeScript 首先会尝试将表达式做为无状态函数组件进行解析。如果解析成功,那么 TypeScript 就完成了表达式到其声明的解析操作。如果按照无状态函数组件解析失败,那么 TypeScript 会继续尝试以类组件的形式进行解析。如果依旧失败,那么将输出一个错误。

    无状态函数组件

    注释:下例应该是 React 函数组件的写法。Vue 不同。

    正如其名,组件被定义成 JavaScript 函数,它的第一个参数是props对象。 TypeScript 会强制它的返回值可以赋值给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。 它应该使用单一的属性来定义。 这个属性名之后会被使用。 TypeScript 2.8,如果未指定JSX.ElementAttributesProperty,那么将使用类元素构造函数或 SFC 调用的第一个参数的类型。

    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-*属性),并且它没出现在元素属性类型里时不会当做一个错误。

    另外,JSX 还会使用JSX.IntrinsicAttributes接口来指定额外的属性,这些额外的属性通常不会被组件的 props 或 arguments 使用 - 比如 React 里的key。还有,JSX.IntrinsicClassAttributes<T>泛型类型也可以用来做同样的事情。这里的泛型参数表示类实例类型。在 React 里,它用来允许Ref<T>类型上的ref属性。通常来讲,这些接口上的所有属性都是可选的,除非你想要用户在每个 JSX 标签上都提供一些属性。

    延展操作符也可以使用:

    var props = { requiredProp: 'bar' };
    <foo {...props} />; // 正确
    
    var badProps = {};
    <foo {...badProps} />; // 错误
    

    子孙类型检查

    注释:插槽类型的检查。在 vue 中不建议使用插槽,全部使用作用域插槽替换。

    从 TypeScript 2.3 开始,我们引入了 children 类型检查。children 是_元素属性 (attribute) 类型_的一个特殊属性 (property),子 JSXExpression 将会被插入到属性里。 与使用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>
    
    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结果类型

    默认地 JSX 表达式结果的类型为any。 你可以自定义这个类型,通过指定JSX.Element接口。 然而,不能够从接口里检索元素,属性或 JSX 的子元素的类型信息。 它是一个黑盒。

    React整合

    要想一起使用 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} />; // 错误
    

    工厂函数

    jsx: react编译选项使用的工厂函数是可以配置的。可以使用jsxFactory命令行选项,或内联的@jsx注释指令在每个文件上设置。比如,给createElement设置jsxFactory<div />会使用createElement("div")来生成,而不是React.createElement("div")

    注释指令可以像下面这样使用(在 TypeScript 2.8 里):

    import preact = require("preact");
    /* @jsx preact.h */
    const x = <div />;
    

    生成:

    const preact = require("preact");
    const x = preact.h("div", null);
    

    工厂函数的选择同样会影响JSX命名空间的查找(类型检查)。如果工厂函数使用React.createElement定义(默认),编译器会先检查React.JSX,之后才检查全局的JSX。如果工厂函数定义为h,那么在检查全局的JSX之前先检查h.JSX

  • 相关阅读:
    框架学习之Spring 前言
    XML学习第二节 DTD介绍
    JavaScript重学 V512视频
    框架学习之Spring 第五节 SSH整合开发[Spring2.5+Hibernate3.3+Struts2]
    XML学习第一节 XML简介
    框架学习之Spring 第四节 Spring集成JDBC组件开发
    歌曲:酒干倘卖无 背后的故事
    又要被学校开除了!
    linux常用命令
    心情
  • 原文地址:https://www.cnblogs.com/qq3279338858/p/14365316.html
Copyright © 2020-2023  润新知