Expo 类型生成参考

npm

expo-type-information 包的参考文档。


For the complete documentation index, see llms.txt. Use this file to discover all available pages.

expo-type-information 库仅适用于 macOS。适用于 SDK 56 及更高版本。

expo-type-information 包提供了用于自动为 Swift 模块生成 TypeScript 接口的工具。它由多个部分组成:

  • 基于 sourcekitten 的 Swift 解析器:用于从 Swift Expo 模块中检索并构造类型信息的解析器。
  • 类型抽象:对与 Expo 模块相关的类型信息进行抽象,解析器会以这种抽象后的方式返回信息。
  • TypeScript AST 生成器:一组帮助生成 TypeScript 代码的函数。
  • CLI:一个命令行工具,集成了上述功能。

配置

安装 expo-type-information 库:

Terminal
npx expo install expo-type-information

使用此包还需要安装 sourcekitten。你可以使用 macOS 包管理器,例如 Homebrew。

Terminal
brew install sourcekitten

CLI 参考

通用 CLI 选项

该库中的每个 CLI 命令都会使用以下通用选项进行配置。唯一的例外是 inline-modules-interface,它的选项略有不同。

标志描述默认值
-i, --input-paths <filePaths...>某个模块的 Swift 文件路径,允许使用 glob 模式。
-m --module-path <modulePath>Expo 模块根目录的路径。
-o, --output-path <filePath>用于保存生成结果的路径。如果不提供此选项,则会将生成结果打印到控制台。
-t, --type-inference <typeInference>类型推断级别:NO_INFERENCESIMPLE_INFERENCEPREPROCESS_AND_INFERENCE。请注意,PREPROCESS_AND_INFERENCE 选项在某些模块上偶尔会失败。如果遇到错误,请回退到 SIMPLE_INFERENCENO_INFERENCESIMPLE_INFERENCE
-s, --skip-unicode-character-mapping跳过将文件中的所有非 ASCII 字符映射为 ASCII 字符串。默认情况下会执行此映射,因为 SourceKitten 在计算非 ASCII 字符的偏移量时表现不一致。
-w --watcher启动一个监听器,用于检查 input-path 文件的更改。

主要命令

module-interface

为 Swift 模块生成完整的 TypeScript 接口。它由以下内容组成:

  • 包含模块中定义的所有类型的 types.ts 文件
  • 包含原生模块定义的 module.ts
  • 模块中定义的每个视图对应的 view.tsx
  • 重新导出某些函数的 index.ts 文件

接受标准 通用 CLI 选项

inline-modules-interface

为项目中的每个 Swift 内联模块创建 TypeScript 接口。该接口由两个文件组成:

  • Module.generated.ts:每次运行该命令都会重新生成
  • Module.tsx:如果你修改了它,则不会被重新生成

选项:

标志描述默认值
-a --app-json <appJsonPath>应用配置 文件的路径,其中定义了 inline.modules.watchedDirectories
-w --watcher启动一个监听器,用于检查内联模块文件的更改。
-t, --type-inference <typeInference>类型推断级别:NO_INFERENCESIMPLE_INFERENCEPREPROCESS_AND_INFERENCE。请注意,PREPROCESS_AND_INFERENCE 选项在某些模块上偶尔会失败。如果遇到错误,请回退到 SIMPLE_INFERENCENO_INFERENCESIMPLE_INFERENCE

short-module-interface

为 Expo 模块创建一个简短的 TypeScript 接口。会覆盖 ModuleName.generated.ts,并在不存在时创建 ModuleName.ts。可与 inline-modules 一起使用。

接受标准 通用 CLI 选项

generate-mocks-for-file

为给定的 expo 模块生成 mock。

接受标准 通用 CLI 选项

其他命令

这些命令是内部命令或非常特定的命令。

本节中的所有命令都接受标准 通用 CLI 选项

other type-information

解析 Swift 模块类型信息并输出 FileTypeInformation JSON。

other generate-module-types

生成模块的类型声明文件内容。

other generate-view-types

生成原生 View 的类型声明文件。

other generate-jsx-intrinsics

生成 View 的声明文件,并使用该 View 的 props 更新 JSX intrinsic。

other preprocess-file

在通过 sourcekitten 解析之前,打印处于预处理状态的文件。它有助于检查 --module-path--input-path--type-inference 选项如何影响解析后的文件。

类型信息抽象

deserializeTypeInformation(fileTypeinformationSerialized)

ParameterTypeDescription
fileTypeinformationSerializedFileTypeInformationSerialized

FileTypeInformationSerialized object to deserialize.


Used for testing purposes, maps Arrays to Sets and Maps depending on the field and returns FileTypeInformation object.

FileTypeInformation object.

getFileTypeInformation(options)

ParameterTypeDescription
optionsGetFileTypeInformationOptions

Configuration object containing the input source (file or string) and the desired level of type inference.


Reads and extracts FileTypeInformation from either a provided file path or a raw string of source code. If a raw string is provided, or if the PREPROCESS_AND_INFERENCE inference option is selected, the function will create a temporary file with the (optionally preprocessed) content to facilitate parsing.

A promise that resolves to a FileTypeInformation object if the input was parsed successfully. Otherwise, it resolves to null.

serializeTypeInformation(fileTypeinformation)

ParameterTypeDescription
fileTypeinformationFileTypeInformation

FileTypeInformation object to serialize.


Used for testing purposes, maps Sets and Maps to Arrays and returns FileTypeInformationSerialized object which can be written to a JSON.

a FileTypeInformationSerialized object.

TypeScript 生成

generateConciseTsInterface(fileTypeInformation)

ParameterTypeDescription
fileTypeInformationFileTypeInformation

The abstracted type information of an Expo module.


Generates a short TypeScript interface for an Expo module. This creates the content for two files: a volatile generated file containing raw type definitions, and a stable user-facing file that wraps and exports the native module methods in new functions.

Returns:
Promise<{ moduleTypescriptInterfaceFileContent: string, volatileGeneratedFileContent: string }>

A promise that resolves to an object containing the string contents for both the volatile generated file and the stable TypeScript interface file.

generateFullTsInterface(fileTypeInformation)

ParameterTypeDescription
fileTypeInformationFileTypeInformation

The abstracted type information of an Expo module.


Generates a full, multi-file TypeScript interface for an Expo module. The generated interface is separated into a file with type definitions, a file which wraps the native module, a file for each view defined in a module and an index file which reexports all definitions from the other files.

Returns:
Promise<{ indexFile: OutputFile, moduleNativeFile: OutputFile, moduleTypesFile: OutputFile, moduleViewsFiles: OutputFile[] } | null>

A promise that resolves to an object containing the string contents for all of the generated files or null if the generation has failed.

generateJSXIntrinsicsFileContent(fileTypeInformation)

ParameterTypeDescription
fileTypeInformationFileTypeInformation

The abstracted type information of an Expo module.


Generates the TypeScript string content for a native View's type declaration file which mounts the View props on the global JSXIntrinsics.

Returns:
Promise<string | null>

A promise that resolves to a string containing the TypeScript declaration file content or null if the generation has failed.

generateModuleTypesFileContent(fileTypeInformation)

ParameterTypeDescription
fileTypeInformationFileTypeInformation

The abstracted type information of an Expo module.


Generates the TypeScript string content for a native module type declaration file.

Returns:
Promise<string | null>

A promise that resolves to a string containing the TypeScript module declaration file content or null if the generation has failed.

generateViewTypesFileContent(fileTypeInformation)

ParameterTypeDescription
fileTypeInformationFileTypeInformation

The abstracted type information of an Expo module.


Generates the TypeScript string content for a native View's type declaration file.

Returns:
Promise<string | null>

A promise that resolves to a string containing the TypeScript declaration file content or null if the generation has failed.

Mock 生成

generateMocks(files, outputLanguage)

ParameterTypeDescription
filesFileTypeInformation[]

A list of FileTypeInformation objects with generated type information for multiple modules

outputLanguage(optional)'typescript' | 'javascript'

the language to emit the mocks in

Default:'javascript'

This function generates JavaScript/TypeScript mocks for each provided FileTypeInformation object.

Returns:
Promise<void>

nothing

getAllExpoModulesInWorkingDirectory()

Component

withPreparedSingleFile

Type: React.Element<GetFileTypeInformationOptions>

Types

AnonymousType

Literal Type: union

Represents an anonymous type, a one that is not named instead written directly in the code, such as inline generics, arrays, or optionals.

Acceptable values are: ParametrizedType | SumType | OptionalType | DictionaryType | ArrayType

Argument

Represents an argument passed to a function or constructor.

PropertyTypeDescription
namestring | undefined
-
typeType
-

ArrayType

Type: Type

Represents a list or array of a specific type.

Note: The information that this type is array is implicit and exists only in the type system and on the parent type. There is no field on the ArrayType object that explicitly indicates that.

ClassDeclaration

Represents a DSL native class declaration.

Type: DefinitionOffset extended by:

PropertyTypeDescription
asyncMethodsFunctionDeclaration[]
-
constructorConstructorDeclaration | null
-
methodsFunctionDeclaration[]
-
namestring
-
propertiesPropertyDeclaration[]
-

ConstantDeclaration

Represents a DSL constant declaration.

Type: DefinitionOffset extended by:

PropertyTypeDescription
namestring
-
typeType
-

ConstructorDeclaration

Represents a DSL class constructor declaration.

Type: DefinitionOffset extended by:

PropertyTypeDescription
argumentsArgument[]
-

DefinitionOffset

Retains information of where the thing was defined in the file. As collecting type information is written in asynchronous way it is non-deterministic. To make it deterministic we just sort the declaration by the definitionOffset, maintaining the same ordering as in original file.

PropertyTypeDescription
definitionOffsetnumber
-

DictionaryType

Represents a dictionary type, defining the explicit types for its keys and values.

PropertyTypeDescription
keyType
-
valueType
-

EnumCase

Represents a single case inside an enum declaration.

Type: string

EnumType

Represents an enum type, containing its name and all associated cases.

PropertyTypeDescription
casesEnumCase[]
-
namestring
-

EventDeclaration

Represents a DSL event declaration.

Type: string

Field

Type: Argument

Represents a single field within a record or a struct.

FileInputOption

Defines an input option for extracting type information from a set of physical files.

PropertyTypeDescription
inputFileAbsolutePathsstring[]
-
type'file'
-

FileTypeInformation

FileTypeInformation object abstracts over type related information in a file. The abstraction is closely related to Typescript and expo NativeModules (both to be independent of the actual native side and to give accurate information about what and how we can use the given module).

PropertyTypeDescription
declaredTypeIdentifiersSet<string>
-
enumsEnumType[]
-
inferredTypeParametersCountMap<string, number>
-
moduleClassesModuleClassDeclaration[]
-
recordsRecordType[]
-
typeIdentifierDefinitionMapTypeIdentifierDefinitionMap
-
usedTypeIdentifiersSet<string>
-

FileTypeInformationSerialized

Serialized version of the FileTypeInformation, suitable for JSON storage or testing environments.

PropertyTypeDescription
declaredTypeIdentifiersListstring[]
-
enumsEnumType[]
-
inferredTypeParametersCountListundefined
-
moduleClassesModuleClassDeclaration[]
-
recordsRecordType[]
-
typeIdentifierDefinitionListTypeIdentifierDefinitionList
-
usedTypeIdentifiersListstring[]
-

FunctionDeclaration

Represents a DSL function declaration.

Type: DefinitionOffset extended by:

PropertyTypeDescription
argumentsArgument[]
-
namestring
-
parametersType[]
-
returnTypeType
-

GetFileTypeInformationOptions

Options specifying the input source and inference level for retrieving type information.

PropertyTypeDescription
inputStringInputOption | FileInputOption

The input source, provided either as a direct string or a file path.

mapUnicodeCharactersboolean

An option to map unicode code points to ASCII strings to fix underlying SourceKit issue.

typeInference(optional)TypeInferenceOption

The desired level of type inference. Defaults to PREPROCESS_AND_INFERENCE if omitted.

IdentifierDefinition

Represents a definition of an identifier.

PropertyTypeDescription
definitionstring | RecordType | EnumType | ClassDeclaration
-
kindIdentifierKind
-

ModuleClassDeclaration

Represents a DSL module declaration.

Type: DefinitionOffset extended by:

PropertyTypeDescription
asyncFunctionsFunctionDeclaration[]
-
classesClassDeclaration[]
-
constantsConstantDeclaration[]
-
constructorConstructorDeclaration | null
-
eventsEventDeclaration[]
-
functionsFunctionDeclaration[]
-
namestring
-
propertiesPropertyDeclaration[]
-
propsPropDeclaration[]
-
viewsViewDeclaration[]
-

OptionalType

Type: Type

Represents an optional type that can also resolve to null or undefined.

Note: The information that this type is optional is implicit and exists only in the type system and on the parent type. There is no field on the OptionalType object that explicitly indicates that.

OutputFile

A helper type which contains the generated file content and name.

PropertyTypeDescription
contentstring
-
namestring
-

ParametrizedType

Represents a parametrized type, that is a generic type with specified parameters e.g. Map<string, number>.

PropertyTypeDescription
nameTypeIdentifier
-
typesType[]
-

PropDeclaration

Represents a DSL prop declaration.

Type: DefinitionOffset extended by:

PropertyTypeDescription
argumentsArgument[]
-
namestring
-

PropertyDeclaration

Type: ConstantDeclaration

Represents a DSL property declaration.

RecordType

Represents a struct or dictionary-like record consisting of named fields.

PropertyTypeDescription
fieldsField[]
-
namestring
-

StringInputOption

Defines an input option for extracting type information directly from a raw string of source code.

PropertyTypeDescription
fileContentstring
-
language'Swift'
-
type'string'
-

SumType

Represents a union or a sum type where a value can be one of several different types.

PropertyTypeDescription
typesType[]
-

Type

Represents an abstract type node.

PropertyTypeDescription
kindTypeKind
-
typeBasicType | TypeIdentifier | AnonymousType
-

TypeIdentifier

Represents a type identifier as a string reference.

Type: string

TypeIdentifierDefinitionList

Type: undefined

Serialized version of the TypeIdentifierDefinitionMap.

TypeIdentifierDefinitionMap

Type: Map<string, IdentifierDefinition>

Maps type identifier strings to their definition objects.

ViewDeclaration

Type: ModuleClassDeclaration

Represents a DSL view declaration.

Enums

BasicType

Represents a basic type that is not user defined.

ANY

BasicType.ANY = 0

STRING

BasicType.STRING = 1

NUMBER

BasicType.NUMBER = 2

BOOLEAN

BasicType.BOOLEAN = 3

VOID

BasicType.VOID = 4

UNDEFINED

BasicType.UNDEFINED = 5

UNRESOLVED

BasicType.UNRESOLVED = 6

Represents a type that couldn't be resolved

IdentifierKind

Represents the kind of a parsed identifier from a native file.

BASIC

IdentifierKind.BASIC = 0

ENUM

IdentifierKind.ENUM = 1

RECORD

IdentifierKind.RECORD = 2

CLASS

IdentifierKind.CLASS = 3

TypeInferenceOption

Defines the level of type inference to apply when extracting type information.

Note: In case where type inference is on, it may take more then twice the time to compute the type information.

NO_INFERENCE

TypeInferenceOption.NO_INFERENCE = 0

No type inference will be performed.

SIMPLE_INFERENCE

TypeInferenceOption.SIMPLE_INFERENCE = 1

Basic type inference will be applied.

PREPROCESS_AND_INFERENCE

TypeInferenceOption.PREPROCESS_AND_INFERENCE = 2

Preprocesses the file by injecting returns to extract more type info from sourcekitten.

TypeKind

Categorizes the type node within the abstract syntax tree.

BASIC

TypeKind.BASIC = 0

IDENTIFIER

TypeKind.IDENTIFIER = 1

SUM

TypeKind.SUM = 2

PARAMETRIZED

TypeKind.PARAMETRIZED = 3

OPTIONAL

TypeKind.OPTIONAL = 4

ARRAY

TypeKind.ARRAY = 5

DICTIONARY

TypeKind.DICTIONARY = 6

Swift 解析器限制

expo-type-information 库使用 sourcekitten 来解析 Swift 文件。解析 Swift 文件是一项复杂的任务,目前并非所有内容都已实现。

关于当前版本 Swift 文件解析的已知问题
  • 嵌套类不会被完整解析。

    Sourcekitten 在解析嵌套闭包方面存在限制,因此你模块中定义的类可能无法被完全解析。这就是为什么如果模块中存在 DSL Class,其方法的返回类型会显示为 unresolved 的原因。

  • 返回类型解析,PREPROCESS_AND_INFERENCE 推断选项。

    当闭包的返回类型未显式提供时,工具需要对其进行推断。 在 sourcekitten 中,一种做法是:当存在 return identifier 语句时,我们可以询问该 identifier 的类型。 第三个推断选项 PREPROCESS_AND_INFERENCE 会重写文件,使得对于每个 return expression 语句, 都插入一条新的 let return_expression = expression; return return_expression;,这样我们就可以询问标识符类型。 已知重写有时会出现问题(主要是由于字符串和注释),因此它不一定总能正常工作。 目前也没有办法解析没有 return 的返回,即返回表达式作为闭包尾部表达式的情况。

  • 不支持的 Expo Module DSL 声明。

    目前并非所有 DSL 声明都会被解析,而且有些声明在任何上下文中都不会被解析。例如,Events 会在 View 内部被解析,但不会在 Module 定义中被解析。

  • 使用 Unicode 字符会破坏 sourcekitten 的偏移量。

支持的 Expo modules DSL 声明

特性说明和限制
Expo DSL 声明支持解析:AsyncFunctionConstantConstructorEventsFunctionNamePropPropertyView
Swift structclass必须符合 Record 协议。仅解析带有 @Field 注解标记的属性。
Swift enum支持基础 case。当前不会解析与 enum case 关联的值。