> 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.

# TypeScript

Lynx 通过 Rsbuild 支持 TypeScript。代码转换、路径别名、`tsconfig.json` 配置和类型检查方式见 [Rsbuild 的 TypeScript 指南](https://rsbuild.rs/zh/guide/basic/typescript)。**代码转换不会执行类型检查**，需要另行配置类型检查插件或运行 `tsc`。

CSS Modules、静态资源等构建期类型使用 [Rsbuild 的预设类型](https://rsbuild.rs/zh/guide/basic/typescript#preset-types)，在已有的 `compilerOptions.types` 中追加 `@rsbuild/core/types`。

## 扩展 Lynx 类型

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

- [`GlobalProps`](#globalprops)：扩展 `lynx.__globalProps` 的类型定义
- [`InitData`](#initdata)：扩展 [`useInitData()`](/next/zh/api/react/Hooks/useInitData.md) 的返回类型
- [`IntrinsicElements`](#intrinsicelements): 扩展元件的类型（例如：可以为 `<input>` 元件定义类型）
- [`NativeModules`](#nativemodules): 扩展[原生模块](/next/zh/guide/use-native-modules.md)的类型定义

### GlobalProps

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

```ts title="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` 来添加自定义数据属性：

```ts title="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` 来添加你的[自定义元件](/next/zh/guide/custom-native-component.md)类型定义。

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

```ts title="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` 来添加自定义[原生模块](/next/zh/guide/use-native-modules.md)。

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

```ts title="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 {}; // 这个导出使文件成为一个模块
```
