For AI agents: the complete documentation index is available at /next/zh/llms.txt, the full documentation bundle is available at /next/zh/llms-full.txt, and this page is available as Markdown at /next/zh/guide/build/typescript.md.
Lynx
  • 简体中文
  • TypeScript

    Lynx 通过 Rsbuild 支持 TypeScript。代码转换、路径别名、tsconfig.json 配置和类型检查方式见 Rsbuild 的 TypeScript 指南。代码转换不会执行类型检查,需要另行配置类型检查插件或运行 tsc。

    CSS Modules、静态资源等构建期类型使用 Rsbuild 的预设类型,在已有的 compilerOptions.types 中追加 @rsbuild/core/types。

    扩展 Lynx 类型

    Lynx 提供了默认类型,但你可能需要为你的应用扩展或自定义某些类型定义。

    GlobalProps

    你可以扩展 @lynx-js/types 中的 interface GlobalProps 来添加自定义属性:

    src/global-props.d.ts
    declare module '@lynx-js/types' {
      interface GlobalProps {
        foo: string;
        bar: number;
      }
    }
    
    export {}; // 这个导出使文件成为一个模块

    完成此扩展后,TypeScript 将识别并为 lynx.__globalProps.foo 和 lynx.__globalProps.bar 提供类型检查。

    InitData

    你可以扩展 @lynx-js/react 中的 interface InitData 来添加自定义数据属性:

    src/init-data.d.ts
    declare module '@lynx-js/react' {
      interface InitData {
        foo: string;
        bar: number;
      }
    }
    
    export {}; // 这个导出使文件成为一个模块

    通过这个扩展,TypeScript 将为组件中的 useInitData().foo 和 useInitData().bar 提供类型检查。

    IntrinsicElements

    你可以扩展 @lynx-js/types 中的 interface IntrinsicElements 来添加你的自定义元件类型定义。

    以下是一个 <input> 元件的示例,它具有必需的 type 属性和可选的 bindinput 和 value 属性。

    src/intrinsic-element.d.ts
    import * as Lynx from '@lynx-js/types';
    
    declare module '@lynx-js/types' {
      interface IntrinsicElements extends Lynx.IntrinsicElements {
        input: {
          bindinput?: (e: { type: 'input'; detail: { value: string } }) => void;
          type: string;
          value?: string | undefined;
        };
      }
    }

    NativeModules

    你可以扩展 @lynx-js/types 中的 interface NativeModules 来添加自定义原生模块。

    下面这个示例定义了一个有三个方法的 NativeLocalStorageModule 模块:

    src/native-modules.d.ts
    declare module '@lynx-js/types' {
      interface NativeModules {
        NativeLocalStorageModule: {
          clearStorage(): void;
          getStorageItem(key: string): string | null;
          setStorageItem(key: string, value: string): void;
        };
      }
    }
    
    export {}; // 这个导出使文件成为一个模块
    除非另有说明,本项目采用知识共享署名 4.0 国际许可协议进行许可,代码示例采用 Apache License 2.0 许可协议进行许可。