> This page is for SDK, version Current (default).
> For other versions, use one of these documentation indexes:
> - Current (default): https://buildwithfern.com/learn/sdks/current/llms.txt
> - Legacy: https://buildwithfern.com/learn/sdks/legacy/llms.txt

> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt.

# TypeScript 配置

> 使用 Fern 配置 TypeScript SDK 生成。自定义命名空间、启用序列化层、管理依赖项和控制文件输出。

您可以在 `generators.yml` 中自定义 TypeScript SDK 生成器的行为：

**`generators.yml`**

```yml {6-9} title="generators.yml"
groups:
  ts-sdk:
    generators:
      - name: fern-typescript-sdk
        version: 3.108.0
        config:
          namespaceExport: AcmePayments
          noSerdeLayer: false
          generateSubpackageExports: true
```

**`allowExtraFields`** `boolean`

允许对象模式中未定义的字段。这仅适用于序列化层。

查看 [TypeScript 序列化层](/learn/zh/sdks/generators/typescript/serde-layer) 了解更多信息。

---

**`defaultTimeoutInSeconds`** `number | 'infinity'`

网络请求的默认超时时间。在生成的客户端中，可以在请求级别覆盖此设置。

---

**`enableInlineTypes`** `boolean` — default: true

启用后，内联模式将在 TypeScript 中生成为嵌套类型。
这会产生更简洁的类型名称和更直观的开发者体验。

`enableInlineTypes: false`：

```typescript
// MyRootType.ts
import * as MySdk from "...";

export interface MyRootType {
  foo: MySdk.MyRootTypeFoo;
}

// MyRootTypeFoo.ts
import * as MySdk from "...";

export interface MyRootTypeFoo {
  bar: MySdk.MyRootTypeFooBar;
}

// MyRootTypeFooBar.ts
import * as MySdk from "...";

export interface MyRootTypeFooBar {}
```

`enableInlineTypes: true`：

```typescript
// MyRootType.ts
import * as MySdk from "...";

export interface MyRootType {
  foo: MyRootType.Foo;
}

export namespace MyRootType {
  export interface Foo {
    bar: Foo.Bar;
  }

  export namespace Foo {
    export interface Bar {}
  }
}
```

现在用户可以如下获取深度嵌套的 `Bar` 类型：

```typescript
import { MyRootType } from MySdk;

const bar: MyRootType.Foo.Bar = {};
```

---

**`extraDependencies`** `object` — default: \{}

> **企业功能**
>
> 此功能仅适用于[企业计划](https://buildwithfern.com/pricing)。如需开始使用，请联系 [support@buildwithfern.com](mailto:support@buildwithfern.com)。

在生成的 `package.json` 中指定额外的依赖项。当您向 SDK 添加需要额外依赖项的自定义代码时，这很有用。

```yaml
# generators.yml
config:
  extraDependencies:
    lodash: "3.0.2"
```

---

**`extraDevDependencies`** `object` — default: \{}

> **企业功能**
>
> 此功能仅适用于[企业计划](https://buildwithfern.com/pricing)。如需开始使用，请联系 [support@buildwithfern.com](mailto:support@buildwithfern.com)。

在生成的 `package.json` 中指定额外的开发依赖项。

```yaml
# generators.yml
config:
  extraDevDependencies:
    jest: "29.0.7"
```

> **Note**
>
> 仅适用于发布到 GitHub 时。

---

**`extraPeerDependencies`** `object`

在生成的 `package.json` 中指定额外的对等依赖项：

```yaml
# generators.yml
config:
  extraPeerDependencies:
    react: ">=16.8.0 <19.0.0"
    "react-dom": ">=16.8.0 <19.0.0"
```

---

**`extraPeerDependenciesMeta`** `object`

在生成的 `package.json` 中指定额外的对等依赖项元数据字段：

```yaml
# generators.yml
config:
  extraPeerDependencies:
    react: ">=16.8.0 <19.0.0"
    "react-dom": ">=16.8.0 <19.0.0"
```

---

**`fetchSupport`** `'node-fetch' | 'native'`

选择是否要包含 `node-fetch` 以支持 Node.js 18 之前的版本，或选择 `native` 以使用 Node.js 18 及更高版本中可用的原生 `fetch` API。

---

**`fileResponseType`** `'stream' | 'binary-response'`

更改二进制 HTTP 响应返回给用户的响应类型：

* `stream`：返回流。参见 `streamType`，它控制返回的流类型。
* `binary-response`：返回 `BinaryResponse` 类型，允许用户选择如何消费二进制 HTTP 响应。
  用户可以如下与 `BinaryResponse` 交互：

```typescript
const response = await client.getFile(...);
const stream = response.stream();
// const arrayBuffer = await response.arrayBuffer();
// const blob = await response.blob();
// const bytes = await response.bytes();
const bodyUsed = response.bodyUsed;
```

---

**`formDataSupport`** `'Node16' | 'Node18'`

选择是否要支持 Node.js 16 及以上版本 (`Node16`)，还是 Node.js 18 及以上版本 (`Node18`)。

* `Node16` 使用多个依赖项来支持多部分表单，包括 `form-data`、`formdata-node` 和 `form-data-encoder`。
* `Node18` 使用原生 FormData API，并接受更广泛的文件上传类型，如 `Buffer`、`File`、`Blob`、`Readable`、`ReadableStream`、`ArrayBuffer` 和 `Uint8Array`

---

**`generateSubpackageExports`** `boolean` — default: true

生成子包导出，允许用户直接导入单个客户端，而不是导入整个 SDK。这使 JavaScript 打包器能够摇树优化未使用的代码，显著减少包大小。

```typescript
import { BarClient } from '@acme/sdk/foo/bar';
// 仅导入 Bar 子包

const client = new BarClient({...});
```

启用此选项时，子包导出也会在生成的 `README.md` 中记录。

---

**`includeContentHeadersOnFileDownloadResponse`** `boolean`

包含二进制响应的内容类型和内容长度。用户将收到以下类型的对象：

```typescript
{
    data: <BINARY_RESPONSE_TYPE>;
    contentLengthInBytes?: number;
    contentType?: string;
}
```

`<BINARY_RESPONSE_TYPE>` 是 `core.BinaryResponse` 或流，取决于 `fileResponseType` 设置。

---

**`includeCredentialsOnCrossOriginRequests`** `boolean` — default: false

启用后，在进行网络请求时会将 [`withCredentials`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials) 设置为 `true`。

---

**`includeOtherInUnionTypes`** `boolean`

---

**`includeUtilsOnUnionMembers`** `boolean`

---

**`inlineFileProperties`** `boolean` — default: true

将文件上传属性生成为内联请求属性（而不是位置参数）。

`inlineFileProperties: false`：

```typescript
/**
  * @param {File | fs.ReadStream} file
  * @param {File[] | fs.ReadStream[]} fileList
  * @param {File | fs.ReadStream | undefined} maybeFile
  * @param {File[] | fs.ReadStream[] | undefined} maybeFileList
  * @param {Acme.MyRequest} request
  * @param {Service.RequestOptions} requestOptions - Request-specific configuration.
  *
  * @example
  *     await client.service.post(fs.createReadStream("/path/to/your/file"), [fs.createReadStream("/path/to/your/file")], fs.createReadStream("/path/to/your/file"), [fs.createReadStream("/path/to/your/file")], {})
  */
public async post(
    file: File | fs.ReadStream,
    fileList: File[] | fs.ReadStream[],
    maybeFile: File | fs.ReadStream | undefined,
    maybeFileList: File[] | fs.ReadStream[] | undefined,
    request: Acme.MyRequest,
    requestOptions?: Acme.RequestOptions
): Promise<void> {
  ...
}
```

`inlineFileProperties: true`：

```typescript
/**
  * @param {Acme.MyRequest} request
  * @param {Service.RequestOptions} requestOptions - Request-specific configuration.
  *
  * @example
  *     await client.service.post({
  *        file: fs.createReadStream("/path/to/your/file"),
  *        fileList: [fs.createReadStream("/path/to/your/file")]
  *     })
  */
public async post(
    request: Acme.MyRequest,
    requestOptions?: Service.RequestOptions
): Promise<void> {
  ...
}
```

---

**`inlinePathParameters`** `boolean` — default: true

将路径参数内联到请求类型中。

`inlinePathParameters: false`：

```typescript
await service.getFoo("pathParamValue", { id: "SOME_ID" });
```

`inlinePathParameters: true`：

```typescript
await service.getFoo({ pathParamName: "pathParamValue", id: "SOME_ID" });
```

---

**`namespaceExport`** `string`

自定义生成的 SDK 中导出的命名空间和客户端类名。必须使用 PascalCase。

默认情况下，名称从 API 定义中定义的组织和 API 名称派生：

```typescript
import { AcmeApi, AcmeApiClient } from "@acme/node";
```

设置 namespaceExport 会覆盖这些默认名称：

**`generators.yml`**

```yaml title="generators.yml"
config:
  namespaceExport: AcmePayments
```

```typescript
import { AcmePayments, AcmePaymentsClient } from "@acme/node";
```

---

**`maxRetries`** `number`

失败请求的默认重试次数。未设置时，生成的 SDK 使用自己的内置默认值。SDK 用户仍可通过请求选项按请求覆盖此设置。

---

**`naming`** `string | object`

自定义命名空间导出和类/类型名称。接受字符串简写或完整对象。

**字符串简写** — 设置命名空间并通过 PascalCase 派生所有类名：

**`generators.yml`**

```yaml title="generators.yml"
config:
  naming: acme
```

```typescript
import { acme, AcmeClient } from "acme";
```

**对象形式** — 覆盖单独的名称：

**`generators.yml`**

```yaml title="generators.yml"
config:
  naming:
    namespace: acme
    client: AcmeSdkClient
    error: AcmeSdkError
    environment: AcmeSdkEnvironment
```

```typescript
import { acme, AcmeSdkClient } from "acme";
```

| 字段                | 类型       | 描述                                                        |
| ----------------- | -------- | --------------------------------------------------------- |
| `namespace`       | `string` | 命名空间导出名称。等同于 `namespaceExport`。                           |
| `client`          | `string` | 客户端类名（默认：`${PascalCase(namespace)}Client`）。               |
| `error`           | `string` | 通用 API 错误类名（默认：`${PascalCase(namespace)}Error`）。          |
| `timeoutError`    | `string` | 超时错误类名（默认：`${PascalCase(namespace)}TimeoutError`）。        |
| `environment`     | `string` | 环境枚举名（默认：`${PascalCase(namespace)}Environment`）。          |
| `environmentUrls` | `string` | 环境 URL 类型名（默认：`${PascalCase(namespace)}EnvironmentUrls`）。 |
| `version`         | `string` | 版本枚举名（默认：`${PascalCase(namespace)}Version`）。              |

`namespaceExport` 仍支持向后兼容，但 `naming.namespace` 优先级更高。

---

**`neverThrowErrors`** `boolean` — default: false

启用后，当从服务器接收到非 200 响应时，客户端不会抛出错误。相反，响应会被包装在 [`ApiResponse`](https://github.com/fern-api/fern/blob/main/seed/ts-sdk/alias/src/core/fetcher/APIResponse.ts) 中。

```typescript
const response = await client.callEndpoint(...);
if (response.ok) {
  console.log(response.body)
} else {
  console.error(respons.error)
}
```

---

**`noOptionalProperties`** `boolean` — default: false

默认情况下，Fern 的 `optional<>` 属性会转换为可选的 TypeScript 属性：

```yaml {4}
Person:
  properties:
    name: string
    age: optional<integer>
```

```typescript {3}
interface Person {
  name: string;
  age?: number;
}
```

启用 `noOptionalProperties` 后，生成的属性永远不是可选的。相反，类型使用 `| undefined` 生成。因此，用户必须显式将属性设置为值或 `undefined`。

```typescript {3}
interface Person {
  name: string;
  age: number | undefined;
}
```

---

**`noSerdeLayer`** `boolean` — default: true

控制是否启用序列化层进行序列化/反序列化。

当 `noSerdeLayer: false` 时，生成的客户端包含自定义序列化代码，将属性名转换为 camelCase，在运行时验证请求/响应，并支持复杂类型。

查看 [TypeScript 序列化层](/learn/zh/sdks/generators/typescript/serde-layer) 了解何时启用此选项的详细指导。

---

**`offsetSemantics`** `'item-index' | 'page-index'` — default: item-index

控制如何解释[自动分页](/learn/zh/sdks/deep-dives/auto-pagination)端点的偏移参数。

* `item-index`：偏移计算单个项目（例如，偏移 20 跳过前 20 个项目）。
* `page-index`：偏移计算页面（例如，偏移 3 跳到第 3 页）。

---

**`omitFernHeaders`** `boolean` — default: false

启用后，生成的 SDK 会在 HTTP 请求中省略 `X-Fern-Language`、`X-Fern-SDK-Name` 和 `X-Fern-SDK-Version` 标头。默认情况下包含这些标头以帮助 API 提供者识别 SDK 流量。

---

**`outputSourceFiles`** `boolean` — default: true

控制生成文件的输出格式：

* **当为 `true`（默认）时**：输出原始 TypeScript `.ts` 文件
* **当为 `false` 时**：运行 TypeScript 编译器并输出编译的 `.js` 文件和 `.d.ts` 声明文件

> **Note**
>
> 此选项仅适用于使用本地文件系统输出时。发布到 GitHub 或 npm 时会忽略此设置，文件总是会被编译。

---

**`packageJson`** `object`

当您在 `packageJson` 中指定对象时，它将合并到 `package.json` 文件中。这是自定义 SDK package.json 的推荐方式。

```yaml
# generators.yml
config:
  packageJson:
    description: The SDK for Acme Corp's API.
    author:
      name: Acme Corp
      url: https://developer.acmecorp.com
      email: developers@acmecorp.com
    bugs:
      url: https://developer.acmecorp.com
      email: developers@acmecorp.com
```

您也可以使用 `packageJson.exports` 注册自定义子路径导出（例如 `import { myHelper } from "@acme/sdk/helper"`）。生成器只会为您的 API 定义自动生成导出条目，因此需要手动添加自定义文件—否则 Node.js 不会解析它们的子路径导入。查看[添加自定义代码](/learn/zh/sdks/generators/typescript/custom-code)了解详情。

---

**`package-name`** `string` — default: null

指定用户将从中导入生成的客户端的 TypeScript 包名。

例如，设置 `package-name: "my_custom_package"` 使用户能够使用
`my_custom_package import Client` 来导入您的客户端。

---

**`packagePath`** `string`

指定生成的 SDK 源文件应放置的路径。

---

**`publishToJsr`** `boolean`

将您的 SDK 发布到 [JSR](https://jsr.io/)。启用后，生成器将
生成 `jsr.json` 以及发布到 JSR 的 GitHub 工作流。

---

**`retainOriginalCasing`** `boolean` — default: false

启用后，生成代码中的属性名保留 API 定义中的原始大小写，而不是转换为 camelCase。

```yaml
# generators.yml
config:
  retainOriginalCasing: true
```

**OpenAPI 输入示例：**

```yaml {7, 9}
# OpenAPI schema
components:
  schemas:
    User:
      type: object
      properties:
        user_id:
          type: string
        display_name:
          type: string
```

使用 `retainOriginalCasing: true` 生成的 TypeScript：

```typescript {2-3}
export interface User {
  user_id: string;
  display_name: string;
}
```

使用默认设置生成的 TypeScript（`retainOriginalCasing: false`）：

```typescript {2-3}
export interface User {
  userId: string;
  displayName: string;
}
```

---

**`generateWebSocketClients`** `boolean`

从您的 AsyncAPI 规范生成 WebSocket 客户端。

之前名为 `shouldGenerateWebsocketClients`，仍作为已弃用的别名被接受。

---

**`skipResponseValidation`** `boolean` — default: false

默认情况下，如果服务器的响应与预期类型不匹配（基于 API 规范中响应的建模方式），客户端会抛出错误。

如果 `skipResponseValidation` 设置为 `true`，客户端永远不会因响应格式错误而抛出异常。相反，客户端会使用 `console.warn` 记录问题并返回数据（转换为预期的响应类型）。

> **Warning**
>
> 响应验证只在启用序列化层时发生（`noSerdeLayer: false`）。默认情况下禁用序列化层（`noSerdeLayer: true`）。

---

**`streamType`** `'wrapper' | 'web'`

更改生成的 SDK 中使用的流类型。

* `wrapper`：流使用包装器和多个底层实现来支持 Node.js 18 之前的版本。
* `web`：流使用 Web 标准 `ReadableStream`。

默认值为 `web`。

---

**`treatUnknownAsAny`** `boolean` — default: false

启用 `treatUnknownAsAny` 后，[Fern 中的未知类型会使用 `any` 而不是 `unknown` 类型生成到 TypeScript 中](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#new-unknown-top-type)。

---

**`useBigInt`** `boolean` — default: false

当 `useBigInt` 设置为 `true` 时，会使用自定义的 JSON 序列化器和反序列化器，它会保留 `bigint` 的精度，而不是使用原生的 `JSON.stringify` 和 `JSON.parse` 函数（这些函数会将 `bigint` 转换为 number 而丢失精度）。

当将 `useBigInt` 与我们的序列化层结合使用时（`noSerdeLayer: false`），在 OpenAPI/Fern 规范中标记为 `long` 和 `bigint` 的请求和响应属性将始终为 `bigint`。
但是，当禁用序列化层时（`noSerdeLayer: true`），它们将被类型化为 `number | bigint`。查看 [TypeScript 序列化层](/learn/zh/sdks/generators/typescript/serde-layer) 了解更多信息。

以下是将 `useBigInt` 和 `noSerdeLayer` 与以下 Fern 定义结合使用时生成类型的概述：

*Fern 定义*：

```yaml
types:
  ObjectWithOptionalField:
    properties:
      longProp: long
      bigIntProp: bigint
```

*TypeScript 输出*：

```typescript
// useBigInt: true
// noSerdeLayer: false
interface ObjectWithLongAndBigInt {
  longProp: bigint;
  bigIntProp: bigint;
}

// useBigInt: true
// noSerdeLayer: true
interface ObjectWithLongAndBigInt {
  longProp: bigint | number;
  bigIntProp: bigint | number;
}

// useBigInt: false
// noSerdeLayer: false
interface ObjectWithLongAndBigInt {
  longProp: number;
  bigIntProp: string;
}

// useBigInt: false
// noSerdeLayer: true
interface ObjectWithLongAndBigInt {
  longProp: number;
  bigIntProp: string;
}
```

---

**`useBrandedStringAliases`** `boolean` — default: false

当 `useBrandedStringAliases` 被禁用时（默认），字符串别名生成为
普通的 TypeScript 别名：

```typescript
// 生成的代码

export type MyString = string;

export type OtherString = string;
```

启用 `useBrandedStringAliases` 后，字符串别名会生成为品牌字符串。这使每个别名感觉像它自己的类型并改善编译时安全性。

```yaml
# fern 定义

types:
	MyString: string
	OtherString: string
```

```typescript
// 生成的代码

export type MyString = string & { __MyString: void };
export const MyString = (value: string): MyString => value as MyString;

export type OtherString = string & { __OtherString: void };
export const OtherString = (value: string): OtherString => value as OtherString;
```

```typescript
// 使用生成的类型

function printMyString(s: MyString): void {
  console.log("MyString: " + s);
}

// 不编译，"foo" 不能赋值给 MyString
printMyString("foo");

const otherString = OtherString("other-string");
// 不编译，otherString 不能赋值给 MyString
printMyString(otherString);

// 编译通过
const myString = MyString("my-string");
printMyString(myString);
```

---