【问题标题】:React Typescript: Reflection (listing properties of an interface)React Typescript:反射(列出接口的属性)
【发布时间】:2021-12-11 21:59:35
【问题描述】:

我正在为神经网络编写一个基于节点的编辑器,它(当前)使用 tensorflow.js 来创建网络本身。 Tensorflow.js 有一个带有不同工厂函数的层 API,每个工厂函数都有一个接口用于它们的参数。例如

interface DenseLayerArgs {
    units: number, 
    useBias?: boolean, 
    ...
}
const dense(args: DenseLayerArgs): {
...
}

我的目标是自动加载所有这些工厂函数,并基于 Args 界面为每个函数创建一个菜单。由于无法访问普通 TS 中可能未定义的属性,因此解决方案似乎是某种转换器库(例如 https://www.npmjs.com/package/ts-reflection )。但我无法使用我的 create-react-app 和 typescript setup 运行任何自定义转换器。

有没有人能够让 React 与自定义转换器一起工作,或者有其他解决方案来从界面创建菜单?

干杯

【问题讨论】:

    标签: reactjs typescript reflection abstract-syntax-tree react-typescript


    【解决方案1】:

    我推荐 tst-reflect 用于 TypeScript 反射。

    在 README 中有一段 How to Start。你必须使用例如。 ttypescript 让变压器工作。 TypeScript 不支持开箱即用的转换器,只能通过直接调用它们的 Compiler API 来支持。 ttypescript 是某种包装,允许您在 tsconfig 中定义转换器。

    如何开始的副本:

    1. 安装包。
    npm i tst-reflect && npm i tst-reflect-transformer -D
    
    1. 为了使用转换器插件,您需要支持插件的 TypeScript 编译器,例如。打包ttypescript 或者你可以手动使用TypeScript compiler API
    npm i ttypescript -D
    
    1. 将变压器添加到tsconfig.json
    {
        "compilerOptions": {
            // your options...
    
            // ADD THIS!
            "plugins": [
                {
                    "transform": "tst-reflect-transformer"
                }
            ]
        }
    }
    
    1. 现在只需使用 ttsc 而不是 tsc 转换您的代码
    npx ttsc
    

    和 Webpack 的用法:

    修改你的 webpack 配置。使用options.compilerts-loader 设置ttypescript 编译器。

    ({
        test: /\.(ts|tsx)$/,
        loader: require.resolve("ts-loader"),
        options: {
            compiler: "ttypescript"
        }
    })
    

    以及如何用tst-reflect列出接口的属性?

    import { getType, Property} from "tst-reflect";
    
    interface DenseLayerArgs {
        units: number, 
        useBias?: boolean, 
        // ...
    }
    
    const properties: Array<Property> = getType<DenseLayerArgs>().getProperties();
    // Do something with properties...
    

    Property 是:

    interface Property
    {
        /**
         * Property name
         */
        readonly name: string;
        /**
         * Property type
         */
        readonly type: Type;
        /**
         * Optional property
         */
        readonly optional: boolean;
        /**
         * Access modifier
         */
        readonly accessModifier: AccessModifier;
        /**
         * Accessor
         */
        readonly accessor: Accessor;
        /**
         * Readonly
         */
        readonly readonly: boolean;
        /**
         * Returns array of decorators
         */
        getDecorators(): ReadonlyArray<Decorator>;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-24
      • 2012-05-06
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2022-01-22
      • 1970-01-01
      • 2020-02-21
      相关资源
      最近更新 更多