Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Wechat Mini Program API Typings
https://github.com/wechat-miniprogram/api-typings
Admin
Type definitions for APIs of Wechat Mini Program in TypeScript
Tokens:
86,574
Snippets:
397
Trust Score:
8.3
License:
MIT
Update:
3 weeks ago
Context
Chat
Benchmark
54.02
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Get account info synchronously with getAccountInfoSync Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-object.md Shows the signature for getAccountInfoSync and a usage example that retrieves account info and logs the mini program appId. The returned AccountInfo includes miniProgram and plugin, with plugin only present when called inside a plugin. ```ts getAccountInfoSync(): AccountInfo ``` ```ts const accountInfo = wx.getAccountInfoSync() console.log(accountInfo.miniProgram.appId) ``` -------------------------------- ### XrFrame Usage: Register Custom Element, Material, and Instantiate Node Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-xr-frame.md Shows how to use the XrFrame system to register a custom element and material, and instantiate a node. The example imports the XrFrame module, gets the system via wx.getXrFrameSystem(), defines a custom element class extending XrFrame.Element, registers it with registerElement, registers a material factory with registerMaterial, and creates a node with new xrFrameSystem.Element(). ```typescript import * as XrFrame from 'XrFrame' const xrFrameSystem = wx.getXrFrameSystem() // XrFrame.IXrFrameSystem // register a custom element (pattern from test/xr-frame.test.ts) class XRAutoRotateTouchableGLTF extends XrFrame.Element { public readonly defaultComponents: XrFrame.IEntityComponents = Object.assign({ 'mesh-shape': {}, 'auto-rotate': {}, }, xrFrameSystem.GLTFDefaultComponents) public readonly dataMapping: { [key: string]: string[] } = Object.assign({ speed: ['auto-rotate', 'speed'], }, xrFrameSystem.GLTFDataMapping) } xrFrameSystem.registerElement('auto-rotate-touchable-gltf', XRAutoRotateTouchableGLTF) // register a material factory xrFrameSystem.registerMaterial('shining', (scene) => { return scene.createMaterial(scene.assets.getAsset<XrFrame.Effect>('effect', 'shining')) }) // instantiate a node const node = new xrFrameSystem.Element('test', () => {}) node.update() ``` -------------------------------- ### Install miniprogram-api-typings via npm Source: https://github.com/wechat-miniprogram/api-typings/blob/master/README-en.md Install the standalone npm package for WeChat Mini Program API type definitions. ```bash npm install miniprogram-api-typings ``` -------------------------------- ### Usage example for WXWebAssembly.instantiate Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-wasm.md Shows how to define an importObject, instantiate a module, call an exported function, and inspect module metadata without instantiating. ```typescript // importObject: bind functions/memories/tables for the module's imports const imports: WXWebAssembly.Imports = { env: { log: (msg: string) => console.log(msg), // ExportValue = Function | Memory | Table }, } const instance = await WXWebAssembly.instantiate('assets/hello.wasm', imports) // call an exported function const add = instance.exports['add'] as (a: number, b: number) => number console.log(add(1, 2)) // inspect metadata without instantiating const mod = new WXWebAssembly.Module(new Uint8Array(/* wasm bytes */)) console.log(WXWebAssembly.Module.exports(mod)) // ModuleExportDescriptor[] ``` -------------------------------- ### getStorage signature and usage examples (callback and promise) Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-object.md Asynchronous storage read with promisify support. The example shows both callback and promise styles. Supplying any of success/fail/complete yields void; otherwise returns a Promise. ```TypeScript getStorage< T = any, U extends GetStorageOption<T> = GetStorageOption<T> >( option: U ): PromisifySuccessResult<U, GetStorageOption<T>> ``` ```TypeScript // callback style wx.getStorage<string>({ key: 'name', success(res) { console.log(res.data) }, // res.data: string }) // promise style const res = await wx.getStorage<string>({ key: 'name' }) ``` -------------------------------- ### Install @types/wechat-miniprogram via npm Source: https://github.com/wechat-miniprogram/api-typings/blob/master/README-en.md Install the DefinitelyTyped package for WeChat Mini Program API type definitions. ```bash npm install @types/wechat-miniprogram ``` -------------------------------- ### Path2D usage example Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-canvas.md Example of creating a Path2D object and using its cumulative path methods: moveTo, lineTo, and arc. All Path2D methods return void. ```ts const path = canvas.createPath2D() path.moveTo(20, 20) path.lineTo(80, 120) path.arc(50, 50, 30, 0, Math.PI * 2) ``` -------------------------------- ### canIUse signature and usage example Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-object.md Feature detection API. The example shows checking for 'getStorage' and 'request' support. ```TypeScript canIUse( /** 使用 `${API}.${method}.${param}.${option}` 或者 `${component}.${attribute}.${option}` 方式来调用 */ schema: string ): boolean ``` ```TypeScript if (wx.canIUse('getStorage')) { wx.getStorage({ key: 'k' }) } if (wx.canIUse('request')) { /* ... */ } ``` -------------------------------- ### Callback and promise usage examples for wx.getStorage Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wechat-miniprogram-core.md Demonstrates the three usage patterns: callback style with success, promise style with await, and mixing fail/complete to switch to promise. Shows how the type changes based on the option object. ```typescript // Callback style → res arrives in success() wx.getStorage<string>({ key: 'name', success(res) { console.log(res.data) } }) // Promise style → await the result const res = await wx.getStorage<string>({ key: 'name' }) console.log(res.data) // Mixing in fail()/complete() switches the type to Promise too — all callbacks optional: wx.getStorage({ key: 'k', fail(err) { console.error(err.errMsg) } }) // Promise ``` -------------------------------- ### wx.cloud usage examples Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-cloud.md Shows typical usage of wx.cloud: initializing with environment and traceUser, calling functions in callback and promise styles, uploading/downloading files, and performing database operations including queries, adds, and watching a document. ```typescript wx.cloud.init({ env: 'release-xxxx', traceUser: true }) // callback style wx.cloud.callFunction({ name: 'add', data: { a: 1, b: 2 }, success(res) { console.log(res.result) }, fail(err) { console.error(err.errMsg) }, }) // promise style (RQ — callbacks removed) const res = await wx.cloud.callFunction({ name: 'add', data: { a: 1, b: 2 } }) // res.result: AnyObject | string | undefined // files wx.cloud.uploadFile({ cloudPath: 'a/b.txt', filePath: `${wx.env.USER_DATA_PATH}/b.txt` }) const dl = await wx.cloud.downloadFile({ fileID: 'cloud://...' }) console.log(dl.tempFilePath) // database const db = wx.cloud.database() const doc = await db.collection('todos') .where({ done: db.command.eq(false) }) .orderBy('createTime', 'asc') .limit(10) .get() console.log(doc.data) const added = await db.collection('todos').add({ data: { title: 'x' } }) console.log(added._id) // watch a document db.collection('todos').doc('id-1').watch({ onChange(snapshot) { console.log(snapshot.docChanges) }, onError(err) { console.error(err) }, }) ``` -------------------------------- ### require usage examples Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-globals.md Shows synchronous, Promise-based async, and callback-style usage of `require` for importing modules and sub-packages. ```ts // Synchronous const helper = require('./helper') // Async sub-package import — await style const sub = await require.async('some-npm-package') // Callback style require('sub-package-name', (mod) => { console.log(mod) }, (err) => { console.error('load failed', err) }) ``` -------------------------------- ### batchGetStorageSync signature and usage example Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-object.md Synchronous batch storage read. Requires base library 2.25.0 and is not supported in plugins. Throws on failure. The example shows a try/catch block. ```TypeScript batchGetStorageSync( /** 本地缓存中指定的 key 数组 */ keyList: string[] ): any[] ``` ```TypeScript try { const valueList = wx.batchGetStorageSync(['key']) if (valueList) { // Do something with return value } } catch (e) { // Do something when catch error } ``` -------------------------------- ### requirePlugin usage examples Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-globals.md Shows synchronous and Promise-based async usage of `requirePlugin` to import a plugin by its alias. ```ts const pluginApi = requirePlugin('my-plugin-alias') const pluginApi2 = await requirePlugin.async('my-plugin-alias') ``` -------------------------------- ### database Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-cloud.md Gets a database instance for cloud database operations. ```APIDOC ## database ### Description Gets a database instance for cloud database operations. ### Method database ### Parameters - **config** (ICloudConfig) - Optional - Configuration for the database instance. ### Return DB.Database ``` -------------------------------- ### Listen to theme changes with onThemeChange Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-object.md Shows the signature for onThemeChange and a usage example that listens for theme changes and checks if the theme is dark. The callback receives a result with a 'theme' property that can be 'dark' or 'light'. ```ts onThemeChange( /** 系统主题改变事件的监听函数 */ listener: OnThemeChangeCallback ): void ``` ```ts wx.onThemeChange((res) => { if (res.theme === 'dark') { /* switch to dark UI */ } }) ``` -------------------------------- ### new Table(descriptor, value?) Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-wasm.md Creates a new growable table with the given descriptor and optional initial value. Provides methods to get, set, and grow the table. ```APIDOC ## new Table(descriptor, value?) ### Description Creates a new growable table with the given descriptor and optional initial value. Provides methods to get, set, and grow the table. ### Method Constructor ### Endpoint new WXWebAssembly.Table(descriptor, value?) ### Parameters #### Path Parameters - **descriptor** (TableDescriptor) - Required - The table descriptor with `element`, `initial`, and optional `maximum`. - **value** (any) - Optional - The initial value for the table elements. ### Request Example ```ts const table = new WXWebAssembly.Table({ element: 'anyfunc', initial: 10 }) ``` ### Response #### Success Response (Table) - **table** (Table) - The table instance with `length`, `get`, `set`, and `grow` methods. #### Response Example ```ts const table = new WXWebAssembly.Table({ element: 'anyfunc', initial: 10 }) console.log(table.length) // 10 table.set(0, () => {}) console.log(table.get(0)) ``` ``` -------------------------------- ### Create canvas context and offscreen canvas Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-object.md Shows the type signatures for createCanvasContext and createOffscreenCanvas, followed by a usage example that draws a red rectangle and creates an offscreen canvas with a 2D context. ```ts createCanvasContext( canvasId: string, component?: Component.TrivialInstance | Page.TrivialInstance ): CanvasContext createOffscreenCanvas( width: number, height: number, component?: Component.TrivialInstance | Page.TrivialInstance ): OffscreenCanvas createOffscreenCanvas(option: CreateOffscreenCanvasOption): OffscreenCanvas ``` ```ts const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 75) ctx.draw() const off = wx.createOffscreenCanvas({ width: 100, height: 100, type: '2d' }) ``` -------------------------------- ### Console logging and grouping example Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-globals.md Shows basic and grouped console usage. `console.log` prints a session value from `wx.getStorageSync`. `console.group` opens an indented group in the debug panel (dev-tool only; no-op in vConsole), and `console.groupEnd` closes it. ```ts // Basic console.log('session', wx.getStorageSync<string>('session')) // Grouped output console.group('network') console.debug('request started') console.warn('slow response') console.error('request failed') console.groupEnd() ``` -------------------------------- ### getStorageSync signature and typed usage example Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-object.md Synchronous storage read with a generic type parameter. The example shows using the generic to get a number and without it to get any. ```TypeScript getStorageSync<T = any>( /** 本地缓存中指定的 key */ key: string ): T ``` ```TypeScript const n = wx.getStorageSync<number>('count') // n: number const anyVal = wx.getStorageSync('anything') // any ``` -------------------------------- ### init Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-cloud.md Initializes the cloud development environment with optional configuration. ```APIDOC ## init ### Description Initializes the cloud development environment with optional configuration. ### Method init ### Parameters - **config** (ICloudConfig) - Optional - Configuration object for cloud initialization. ### Return void ``` -------------------------------- ### Legacy CanvasContext drawing example Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-canvas.md Uses wx.createCanvasContext to get a CanvasContext, sets fill style and font size, draws a red filled rectangle and text, then calls draw() to render to the canvas. Note: this is the legacy imperative API; the modern object API uses the Canvas component. ```TypeScript const ctx = wx.createCanvasContext('myCanvas') ctx.setFillStyle('red') ctx.fillRect(10, 10, 150, 75) ctx.setFontSize(24) ctx.fillText('hello', 10, 100) ctx.draw() ``` -------------------------------- ### instantiate(path, importObject?) Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-wasm.md Asynchronously loads a WebAssembly module from the given path and returns a Promise that resolves to an Instance. The optional importObject provides the imports for the module. ```APIDOC ## instantiate(path, importObject?) ### Description Asynchronously loads a WebAssembly module from the specified path and returns a Promise that resolves to an Instance. The optional importObject provides the imports for the module. ### Method Function ### Endpoint WXWebAssembly.instantiate(path, importObject?) ### Parameters #### Path Parameters - **path** (string) - Required - The path to the WebAssembly module file. #### Query Parameters - **importObject** (Imports) - Optional - An object containing the imports for the module, such as functions, memories, and tables. ### Request Example ```ts const imports: WXWebAssembly.Imports = { env: { log: (msg: string) => console.log(msg), }, } const instance = await WXWebAssembly.instantiate('assets/hello.wasm', imports) ``` ### Response #### Success Response (Promise<Instance>) - **instance** (Instance) - The resolved Instance object with read-only `exports` property. #### Response Example ```ts const instance = await WXWebAssembly.instantiate('assets/hello.wasm', imports) console.log(instance.exports['add'](1, 2)) ``` ### Error Handling - **CompileError** - Thrown if the module fails to compile. - **LinkError** - Thrown if linking fails. - **RuntimeError** - Thrown if a runtime error occurs. ``` -------------------------------- ### App(options?) Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-app.md Registers the Mini Program app instance with lifecycle callbacks and custom properties. The options parameter is optional and can include lifecycle methods like onLaunch, onShow, onHide, onError, onPageNotFound, onUnhandledRejection, and onThemeChange. ```APIDOC ## App(options?) ### Description Registers the Mini Program app instance with lifecycle callbacks and custom properties. The options parameter is optional and can include lifecycle methods like onLaunch, onShow, onHide, onError, onPageNotFound, onUnhandledRejection, and onThemeChange. ### Method Callable function ### Endpoint Global `App` function ### Parameters #### options (Object) - Optional - **onLaunch** (function) - Optional - Lifecycle callback triggered when the Mini Program initializes. Receives a `LaunchShowOption` object. - **onShow** (function) - Optional - Lifecycle callback triggered when the Mini Program is shown. Receives a `LaunchShowOption` object. - **onHide** (function) - Optional - Lifecycle callback triggered when the Mini Program is hidden. - **onError** (function) - Optional - Error listener. Receives an error string with stack information. - **onPageNotFound** (function) - Optional - Page not found listener. Receives a `PageNotFoundOption` object. - **onUnhandledRejection** (function) - Optional - Listener for unhandled promise rejections. Receives an object with `promise` and `reason`. - **onThemeChange** (function) - Optional - Listener for theme changes. Receives an object with `theme` ('dark' or 'light'). - Additional custom properties can be included and will be merged into the app instance. ### Request Example ```ts App({ onLaunch(options) { console.log(options.path) }, globalData: {} }) ``` ### Response No return value (void). ``` -------------------------------- ### getApp(opts?) Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-app.md Returns the current Mini Program app instance. Optionally allows default implementation when App is not defined, useful for independent subpackages. ```APIDOC ## getApp(opts?) ### Description Returns the current Mini Program app instance. Optionally allows default implementation when App is not defined, useful for independent subpackages. ### Method Callable function ### Endpoint Global `getApp` function ### Parameters #### opts (Object) - Optional - **allowDefault** (boolean) - Optional - If true, returns a default implementation when App is not defined. Properties defined in the default implementation are merged into the App when it is called. Minimum base library 2.2.4. ### Request Example ```ts const app = getApp() ``` ### Response Returns the app instance (`Instance<T>`). ``` -------------------------------- ### request signature and usage example Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-object.md HTTP request API. The example shows a request with ArrayBuffer response type, enabling HTTP/2, and aborting the task. ```TypeScript request< T extends string | IAnyObject | ArrayBuffer = | string | IAnyObject | ArrayBuffer >( option: RequestOption<T> ): RequestTask ``` ```TypeScript const task = wx.request<ArrayBuffer>({ url: 'https://developer.weixin.qq.com', data: { q: '1' }, dataType: 'json', enableHttp2: true, success(res) { // res.data: ArrayBuffer; res.statusCode: number console.log(res.statusCode, res.data) }, fail(err) { console.error(err.errMsg) }, }) task.abort() // cancel the request ``` -------------------------------- ### new Instance(module, importObject?) Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-wasm.md Creates a new live instance of a WebAssembly module. The instance provides read-only access to its exports. ```APIDOC ## new Instance(module, importObject?) ### Description Creates a new live instance of a WebAssembly module. The instance provides read-only access to its exports. ### Method Constructor ### Endpoint new WXWebAssembly.Instance(module, importObject?) ### Parameters #### Path Parameters - **module** (Module) - Required - The compiled WebAssembly module. - **importObject** (Imports) - Optional - The imports for the module. ### Request Example ```ts const instance = new WXWebAssembly.Instance(mod, imports) ``` ### Response #### Success Response (Instance) - **instance** (Instance) - The live instance with read-only `exports` property. #### Response Example ```ts const instance = new WXWebAssembly.Instance(mod, imports) console.log(instance.exports['add'](1, 2)) ``` ``` -------------------------------- ### SharedValue usage example Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-skyline.md Example of creating a plain worklet data object read from a worklet function. The SharedValue consumption is declared but runtime pulls happen inside the Skyline runtime; the typings only fix the shape. ```typescript // plain worklet data object read from a worklet function // (SharedValue consumption is declared but the runtime pulls happen inside // the Skyline runtime — the typings only fix the shape) const shared: WechatMiniprogram.Skyline.SharedValue<number> = { value: 42 } ``` -------------------------------- ### Instance Methods Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-glass-easel.md Methods available on a glass-easel component instance. ```APIDOC ## Instance Methods ### Description Methods available on a glass-easel component instance. ### Methods - `getPageId(): string` - Returns the page ID. - `groupSetData(callback)` - Groups data updates. - `setData(newData, callback?)` - Updates data (two overloads). - `updateData(newData)` - Updates data. - `replaceDataOnPath<T extends Array<string|number>>(path: readonly [...T], data)` - Replaces data at a path. - `spliceArrayDataOnPath<T>(path, index, del, inserts)` - Splices array data at a path. - `applyDataUpdates()` - Applies pending data updates. - `groupUpdates<T>(callback: () => T): T | undefined` - Groups updates. - `hasBehavior(behavior: Behavior.TrivialInstance | TraitBehavior.Instance<any, any>): boolean` - Checks if a behavior is present. - `traitBehavior<TOut>(traitBehavior: TraitBehavior.Instance<any, TOut>): TOut | undefined` - Gets trait behavior data. - `triggerEvent(name, detail?, options?)` - Triggers an event. - `createSelectorQuery()` - Creates a selector query. - `createIntersectionObserver(options?)` - Creates an intersection observer. - `createMediaQueryObserver()` - Creates a media query observer. - `getOpenerEventChannel(): EventChannel` - Gets the opener event channel. - `selectComponent(selector)` - Selects a component. - `selectAllComponents(selector)` - Selects all matching components. - `selectOwnerComponent()` - Selects the owner component. - `getRelationNodes(relationKey)` - Gets relation nodes. - `asInstanceOf<U...>(componentType): Instance<...> | null` - Casts to a specific component type. - `applyAnimatedStyle(selector, updater, userConfig?, callback?)` - Applies animated style (Skyline). - `clearAnimatedStyle(selector, styleIds, callback?)` - Clears animated style. - `applyAnimation(selector, options, _animeJS, callback?)` - Applies animation. - `clearAnimation(selector, options, callback?)` - Clears animation. - `animate(selector, keyframes, duration, callback?)` - Animates with keyframes. - `getTabBar(cb?)` - Gets the tab bar. - `getAppBar()` - Gets the app bar. - `setInitialRenderingCache()` - Sets initial rendering cache. - `setUpdatePerformanceListener<WithDataPath>(config, listener)` - Sets update performance listener. - `getPassiveEvent(cb)` - Gets passive event. - `setPassiveEvent(config)` - Sets passive event. ``` -------------------------------- ### CDN Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-cloud.md Constructor for creating CDN instances. ```APIDOC ## CDN ### Description Constructor for creating CDN instances. ### Method CDN ### Return ICloud.ICDNConstructor ``` -------------------------------- ### getTempFileURL Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-cloud.md Gets temporary file URLs for cloud-stored files. ```APIDOC ## getTempFileURL ### Description Gets temporary file URLs for cloud-stored files. ### Method getTempFileURL ### Parameters - **param** (OQ<GetTempFileURLParam> | RQ<GetTempFileURLParam>) - Required - Parameters for getting temporary file URLs. ### Return - Callback overload: void - Promise overload: Promise<GetTempFileURLResult> ``` -------------------------------- ### App() lifecycle and typed getApp() usage Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-app.md Shows the full App() configuration with lifecycle callbacks and typed getApp() usage. The App() call registers globalData, userInfoReadyCallback, onLaunch, onHide, onError, onPageNotFound, onUnhandledRejection, and onThemeChange. The getApp() calls demonstrate typed instance access and the allowDefault option for standalone sub-packages. ```ts App({ globalData: { userInfo: {} as WechatMiniprogram.UserInfo, }, userInfoReadyCallback(userInfo: WechatMiniprogram.UserInfo) { userInfo.gender }, onLaunch() { const logs: number[] = wx.getStorageSync('logs') || [] logs.unshift(Date.now()) wx.setStorageSync('logs', logs) }, onHide() { console.log('hidden') }, onError(error) { console.error(error) }, onPageNotFound(e) { // e.isEntryPage: boolean wx.redirectTo({ url: '/pages/index/index' }) }, onUnhandledRejection({ reason, promise }) { console.error(reason) }, onThemeChange(res) { // res.theme: 'dark' | 'light' }, }) // Non-lifetime fields become typed instance fields const app = getApp() // WechatMiniprogram.App.Instance<IAnyObject> const typed = getApp<{ greeting(): string }>() typed.greeting() // typed instance // Default implementation for standalone sub-packages getApp({ allowDefault: true }) ``` -------------------------------- ### DocumentReference Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-cloud.md Represents a single document in a collection. Provides methods to get, set, update, remove, and watch the document. ```APIDOC ## DocumentReference ### Description Represents a single document in a collection. Provides methods to get, set, update, remove, and watch the document. ### Methods - **field(object: Record<string, any>): this** - Specifies which fields to return. - **get(options: OQ<IGetDocumentOptions>): void** - Fetches the document. Callback style. - **get(options?: RQ<IGetDocumentOptions>): Promise<IQuerySingleResult>** - Fetches the document. Promise style. - **set(options: OQ<ISetSingleDocumentOptions>): void** - Replaces the document. Callback style. - **set(options?: RQ<...>): Promise<ISetResult>** - Replaces the document. Promise style. - **update(options: OQ<IUpdateSingleDocumentOptions>): void** - Updates the document. Callback style. - **update(options?: RQ<...>): Promise<IUpdateResult>** - Updates the document. Promise style. - **remove(options: OQ<IRemoveSingleDocumentOptions>): void** - Removes the document. Callback style. - **remove(options?: RQ<...>): Promise<IRemoveResult>** - Removes the document. Promise style. - **watch(options: IWatchOptions): RealtimeListener** - Watches for real-time changes. ### Example ```ts const doc = db.collection('todos').doc('todo-id'); doc.get().then(res => console.log(res)); ``` ``` -------------------------------- ### getCurrentPages Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-page.md Gets the current page stack. The first element is the home page, and the last element is the current page. ```APIDOC ## getCurrentPages ### Description Gets the current page stack. The first element is the home page, and the last element is the current page. Do not attempt to modify the page stack; do not call this function in `App.onLaunch`. ### Method `getCurrentPages` (global function) ### Signature ```ts getCurrentPages(): Array<Instance<IAnyObject, IAnyObject>> ``` ### Return Value An array of page instances, where the first element is the home page and the last is the current page. ### Example ```ts const pages = getCurrentPages() const currentPage = pages[pages.length - 1] ``` ``` -------------------------------- ### Create physics scene and simulate with phys3D Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-phys3d.md Creates a PhysSystem with a local debug file, adds box and sphere colliders, a dynamic rigidbody with gravity, simulates per frame, and performs a raycast to report hit results. ```ts const system = new phys3D.PhysSystem({ isNetwork: false, path: `${wx.env.USER_DATA_PATH}/debug.pxd2`, }) system.gravity.SetVector && system.gravity // RawVec3f — use .y etc. system.createScene() const floor = new phys3D.BoxCollider(system, new phys3D.RawVec3f(0, -1, 0), new phys3D.RawVec3f(10, 1, 10)) const ball = new phys3D.SphereCollider(system, new phys3D.RawVec3f(0, 5, 0), 0.5) const body = new phys3D.DynamicRigidbody(system) body.mass = 1 body.AddForce(new phys3D.RawVec3f(0, -9.8, 0), phys3D.ForceMode.kForceModeForce) // per-frame system.Simulate(1 / 60) const hit = new phys3D.RaycastHit() if (system.Raycast(new phys3D.RawVec3f(0, 0, 0), new phys3D.RawVec3f(0, -1, 0), 100, hit)) { console.log(hit.collider.name, hit.distance) } ``` -------------------------------- ### Using GeneralCallbackResult in wx.startBluetoothDevicesDiscovery fail callback Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wechat-miniprogram-core.md Example of a fail callback where res is typed as GeneralCallbackResult & { errCode: number }. Shows how errMsg is accessed. ```typescript wx.startBluetoothDevicesDiscovery({ services: ['FEE7'], fail(res) { // res is typed: GeneralCallbackResult & { errCode: number } console.error(res.errMsg) }, }) ``` -------------------------------- ### InstanceMethods<D> key members (setData, triggerEvent, animate, etc.) Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-component.md Lists the key instance methods with their signatures and version annotations. Note that setData only accepts JSON-able data, is limited to 1024kB per call, and never set a value to undefined; direct this.data mutation does not update the view. ```ts setData( data: Partial<D> & IAnyObject, callback?: () => void // 1.5.0+ ): void hasBehavior(behavior: Behavior.Identifier): void triggerEvent<DetailType = any>( name: string, detail?: DetailType, options?: TriggerEventOption ): void createSelectorQuery(): SelectorQuery createIntersectionObserver(options: CreateIntersectionObserverOption): IntersectionObserver createMediaQueryObserver(): MediaQueryObserver selectComponent(selector: string): TrivialInstance selectAllComponents(selector: string): TrivialInstance[] selectOwnerComponent(): TrivialInstance getRelationNodes(relationKey: string): TrivialInstance[] groupSetData(callback?: () => void): void // 2.4.0+ getTabBar(): TrivialInstance // 2.6.2+ getPageId(): string // 2.7.1+ animate(selector: string, keyFrames: KeyFrame[], duration: number, callback?: () => void): void animate(selector: string, keyFrames: ScrollTimelineKeyframe[], duration: number, scrollTimeline: ScrollTimelineOption): void clearAnimation(selector: string, callback: () => void): void clearAnimation(selector: string, options?: ClearAnimationOptions, callback?: () => void): void getOpenerEventChannel(): EventChannel | EmptyEventChannel // 2.7.3+ applyAnimatedStyle(selector: string, updater: () => Record<string, string>, userConfig?: { immediate: boolean, flush: 'sync' | 'async' }, callback?: (res: { styleId: number }) => void): void // 2.29.0+ clearAnimatedStyle(selector: string, styleIds: number[], callback?: () => void): void // 2.30.1+ setUpdatePerformanceListener<WithDataPath extends boolean = false>( options: SetUpdatePerformanceListenerOption<WithDataPath>, callback?: UpdatePerformanceListener<WithDataPath>): void // 2.12.0+ getPassiveEvent(callback: (config: PassiveConfig) => void): void // 2.25.1+ setPassiveEvent(config: PassiveConfig): void // 2.25.1+ setInitialRenderingCache(dynamicData: IAnyObject | null): void // 2.11.1+ getAppBar(): TrivialInstance // 3.3.1+ ``` -------------------------------- ### Behavior() Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-glass-easel.md The Behavior() chaining API for defining glass-easel behaviors. ```APIDOC ## Behavior() Chaining API ### Description Calling `Behavior()` with no arguments returns a Builder that accumulates data, properties, methods, and behaviors, and finishes with `.register()`. This is the glass-easel behavior definition API. ### Method `Behavior()` ### Parameters None (call with no arguments to get a Builder). ### Returns A Builder object with methods to define the behavior and a `.register()` method to finalize. ### Usage Example ```ts Behavior() .data({ shared: true }) .methods({ log() { console.log('behavior') } }) .register() ``` ``` -------------------------------- ### WechatMiniprogram Core Types and Async Pattern Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wechat-miniprogram-core.md Core type utilities and the async pattern for WeChat Mini Program APIs, including the PromisifySuccessResult type and an example usage of wx.getStorage. ```APIDOC ## Type: IAnyObject ### Description A generic object type used as an escape hatch throughout the WeChat Mini Program API, representing any object with string keys and arbitrary values. ### Definition `Record<string, any>` ### Usage Used for option objects, data maps, and other generic object parameters in API calls. ``` ```APIDOC ## Type: Optional<F> ### Description A utility type that transforms a function type by making its first parameter optional. Used to create optional method signatures in interfaces. ### Definition `F extends (arg: infer P) => infer R ? (arg?: P) => R : F` ### Usage Applied to lifecycle methods to make them optional on instances, e.g., in `Page.Instance`. ``` ```APIDOC ## Type: OptionalInterface<T> ### Description A mapped type that applies `Optional` to every property of an interface, making all methods optional. Used to allow partial implementations of lifecycle interfaces. ### Definition `{ [K in keyof T]: Optional<T[K]> }` ### Usage Used by `Page.Instance` to make all `ILifetime` methods optional. ``` ```APIDOC ## Type: AsyncMethodOptionLike ### Description A constraint type representing an object with an optional `success` callback. Used as a base for promisified API option types. ### Definition `{ success?: (...args: any[]) => void }` ### Usage Serves as a generic constraint for `PromisifySuccessResult`. ``` ```APIDOC ## Type: PromisifySuccessResult<P, T> ### Description A conditional type that determines the return type of an async API method based on the presence of callback options. If the option object includes `success`, `fail`, or `complete`, the return type is `void` (callback style); otherwise, it returns a `Promise` of the success result type. ### Definition `P extends { success: any } ? void : P extends { fail: any } ? void : P extends { complete: any } ? void : Promise<Parameters<Exclude<T['success'], undefined>>[0]>` ### Usage Used in the return type of almost every async `wx.*` method to support both callback and promise styles. ``` ```APIDOC ## Method: wx.getStorage ### Description Retrieves data from local storage. The method is overloaded to support both callback and promise styles based on the provided options. ### Method GET (conceptual) ### Endpoint `wx.getStorage` ### Parameters #### Request Body - **key** (string) - Required - The key of the stored data. - **success** (function) - Optional - Callback for successful retrieval. - **fail** (function) - Optional - Callback for failure. - **complete** (function) - Optional - Callback for completion. ### Request Example ```ts // Callback style wx.getStorage<string>({ key: 'name', success(res) { console.log(res.data) } }) // Promise style const res = await wx.getStorage<string>({ key: 'name' }) console.log(res.data) // With fail callback wx.getStorage({ key: 'k', fail(err) { console.error(err.errMsg) } }) ``` ### Response #### Success Response - **data** (T) - The stored data. #### Response Example ```ts // Callback style res.data // Promise style res.data ``` ``` -------------------------------- ### Page Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-page.md Registers a page in a mini program. Accepts an object with initial data, lifecycle callbacks, and event handlers. ```APIDOC ## Page ### Description Registers a page in a mini program. Accepts an `Object` parameter that specifies the page's initial data, lifecycle callbacks, and event handlers. ### Method `Page` (global function) ### Signature ```ts Page<TData extends DataOption, TCustom extends CustomOption>(options: Options<TData, TCustom>): void ``` ### Parameters - **options** (`Options<TData, TCustom>`) - Required - The page definition object. It includes `data`, lifecycle methods, custom methods, and `options` (component options). The `this` context inside methods is typed as `Instance<TData, TCustom>`. ### Return Value `void` ### Example ```ts Page({ data: { message: 'Hello' }, onLoad(query) { console.log(query) }, onShow() { console.log('Page shown') }, customMethod() { this.setData({ message: 'Updated' }) } }) ``` ``` -------------------------------- ### Side-effect import of miniprogram-api-typings Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/configuration.md Used as the first configuration option to load the global typings by importing the package for its side effects. Place this import at the top of your main TypeScript file. It requires the package to be installed as a dependency. ```ts import 'miniprogram-api-typings'; ``` -------------------------------- ### APIBaseContract class definition Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-cloud.md Defines the contract that all API providers must adhere to for implementing cloud APIs. It includes methods for getting context, callback return, final parameters, and running the API to return a promise. ```typescript class APIBaseContract<PromiseReturn, CallbackReturn, Param extends IAPIParam, Context = any> { getContext(param: Param): Context getCallbackReturn(param: Param, context: Context): CallbackReturn getFinalParam<T extends Param>(param: Param, context: Context): T run<T extends Param>(param: T): Promise<PromiseReturn> } ``` -------------------------------- ### LaunchShowOption interface – onLaunch/onShow parameter Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/api-reference/wx-app.md Defines the `LaunchShowOption` interface used as the parameter for `onLaunch` and `onShow` lifecycle callbacks. Fields include `path`, `query`, `scene`, `shareTicket`, optional `referrerInfo`, `forwardMaterials`, optional `chatType` (1-4), and required `apiCategory`. `chatType` distinguishes WeChat vs enterprise-WeChat and group vs single chat; `apiCategory` is available from base library 2.20.0. ```TypeScript interface LaunchShowOption { /** 打开小程序的路径 */ path: string /** 打开小程序的query */ query: IAnyObject /** 打开小程序的场景值(~170 documented numeric values, e.g. 1000: 其他, 1001: 最近使用, 1011: 扫描二维码 ...) */ scene: SceneValues /** shareTicket,详见 [获取更多转发信息]((转发#获取更多转发信息)) */ shareTicket: string /** 当场景为由从另一个小程序或公众号或App打开时,返回此字段 */ referrerInfo?: ReferrerInfo /** 打开的文件信息数组,只有从聊天素材场景打开(scene为1173)才会携带该参数 */ forwardMaterials: ForwardMaterials[] /** 从微信群聊/单聊打开小程序时,chatType 表示具体类型:1 微信联系人单聊; 2 企业微信联系人单聊; 3 普通微信群聊; 4 企业微信互通群聊 */ chatType?: 1 | 2 | 3 | 4 /** API 类别: 'default' | 'nativeFunctionalized' | 'browseOnly' | 'embedded'(基础库 2.20.0) */ apiCategory: 'default' | 'nativeFunctionalized' | 'browseOnly' | 'embedded' } ``` -------------------------------- ### Triple-slash reference to index.d.ts Source: https://github.com/wechat-miniprogram/api-typings/blob/master/_autodocs/configuration.md A triple-slash reference directive to the package's main typings file. It is the third configuration option, requiring the package to be installed. This method directly references the .d.ts file for global type inclusion. ```ts /// <reference path="node_modules/miniprogram-api-typings/index.d.ts" /> ```