CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-miniprogram-api-typings

Type definitions for APIs of WeChat Mini Program in TypeScript

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

core-apis.mddocs/

Core WeChat APIs

Main WeChat platform APIs including network requests, storage, UI interactions, media operations, device access, and system information.

Capabilities

Network APIs

HTTP requests, file uploads/downloads, and WebSocket connections.

interface Wx {
  /** Make HTTP request */
  request(options: RequestOption): RequestTask;
  
  /** Upload file to server */
  uploadFile(options: UploadFileOption): UploadTask;
  
  /** Download file from server */
  downloadFile(options: DownloadFileOption): DownloadTask;
  
  /** Connect to WebSocket */
  connectSocket(options: ConnectSocketOption): SocketTask;
  
  /** Send WebSocket message */
  sendSocketMessage(options: SendSocketMessageOption): void;
  
  /** Close WebSocket connection */
  closeSocket(options?: CloseSocketOption): void;
}

interface RequestOption {
  /** Request URL */
  url: string;
  /** Request data */
  data?: string | Record<string, any> | ArrayBuffer;
  /** Request headers */
  header?: Record<string, string>;
  /** Request timeout in milliseconds */
  timeout?: number;
  /** HTTP method */
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'PATCH';
  /** Data type */
  dataType?: 'json' | 'other';
  /** Response type */
  responseType?: 'text' | 'arraybuffer';
  /** Success callback */
  success?(res: RequestSuccessCallbackResult): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface RequestTask {
  /** Abort request */
  abort(): void;
  /** Listen for header received */
  onHeadersReceived(callback: (res: any) => void): void;
  /** Remove header received listener */
  offHeadersReceived(callback?: (res: any) => void): void;
}

Usage Examples:

// Make HTTP request
wx.request({
  url: 'https://api.example.com/data',
  method: 'GET',
  header: {
    'Authorization': 'Bearer token'
  },
  success(res) {
    console.log('Data received:', res.data);
  },
  fail(error) {
    console.error('Request failed:', error);
  }
});

// Upload file
wx.uploadFile({
  url: 'https://api.example.com/upload',
  filePath: tempFilePath,
  name: 'file',
  formData: {
    description: 'User avatar'
  },
  success(res) {
    console.log('Upload success:', res);
  }
});

// WebSocket connection
const socketTask = wx.connectSocket({
  url: 'wss://api.example.com/ws'
});

socketTask.onMessage((res) => {
  console.log('Message received:', res.data);
});

socketTask.send({
  data: JSON.stringify({ type: 'ping' })
});

Storage APIs

Local data storage with sync and async operations.

interface Wx {
  /** Set storage data asynchronously */
  setStorage(options: SetStorageOption): void;
  
  /** Set storage data synchronously */
  setStorageSync(key: string, data: any): void;
  
  /** Get storage data asynchronously */
  getStorage(options: GetStorageOption): void;
  
  /** Get storage data synchronously */
  getStorageSync(key: string): any;
  
  /** Remove storage data asynchronously */
  removeStorage(options: RemoveStorageOption): void;
  
  /** Remove storage data synchronously */
  removeStorageSync(key: string): void;
  
  /** Clear all storage data asynchronously */
  clearStorage(options?: ClearStorageOption): void;
  
  /** Clear all storage data synchronously */
  clearStorageSync(): void;
  
  /** Get storage info asynchronously */
  getStorageInfo(options: GetStorageInfoOption): void;
  
  /** Get storage info synchronously */
  getStorageInfoSync(): GetStorageInfoSyncResult;
  
  /** Batch get storage data synchronously */
  batchGetStorageSync(options: BatchGetStorageSyncOption): BatchGetStorageSyncResult;
  
  /** Batch set storage data synchronously */
  batchSetStorageSync(options: BatchSetStorageSyncOption): void;
}

interface SetStorageOption {
  /** Storage key */
  key: string;
  /** Storage data */
  data: any;
  /** Encrypt storage */
  encrypt?: boolean;
  /** Success callback */
  success?(): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface GetStorageOption {
  /** Storage key */
  key: string;
  /** Decrypt storage */
  decrypt?: boolean;
  /** Success callback */
  success?(res: { data: any }): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

Usage Examples:

// Async storage operations
wx.setStorage({
  key: 'userInfo',
  data: { name: 'John', age: 30 },
  success() {
    console.log('Data saved');
  }
});

wx.getStorage({
  key: 'userInfo',
  success(res) {
    console.log('User info:', res.data);
  }
});

// Sync storage operations
wx.setStorageSync('settings', { theme: 'dark' });
const settings = wx.getStorageSync('settings');

// Batch operations
const results = wx.batchGetStorageSync({
  keyList: ['userInfo', 'settings', 'cache']
});

UI APIs

User interface interactions including dialogs, navigation, and loading states.

interface Wx {
  /** Show toast message */
  showToast(options: ShowToastOption): void;
  
  /** Hide toast */
  hideToast(options?: HideToastOption): void;
  
  /** Show modal dialog */
  showModal(options: ShowModalOption): void;
  
  /** Show loading indicator */
  showLoading(options: ShowLoadingOption): void;
  
  /** Hide loading indicator */
  hideLoading(options?: HideLoadingOption): void;
  
  /** Show action sheet */
  showActionSheet(options: ShowActionSheetOption): void;
  
  /** Navigate to page */
  navigateTo(options: NavigateToOption): void;
  
  /** Redirect to page */
  redirectTo(options: RedirectToOption): void;
  
  /** Switch to tab page */
  switchTab(options: SwitchTabOption): void;
  
  /** Navigate back */
  navigateBack(options?: NavigateBackOption): void;
  
  /** Relaunch app */
  reLaunch(options: ReLaunchOption): void;
}

interface ShowToastOption {
  /** Toast message */
  title: string;
  /** Toast icon */
  icon?: 'success' | 'error' | 'loading' | 'none';
  /** Custom icon path */
  image?: string;
  /** Display duration in ms */
  duration?: number;
  /** Mask to prevent touch */
  mask?: boolean;
  /** Success callback */
  success?(): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface ShowModalOption {
  /** Modal title */
  title?: string;
  /** Modal content */
  content?: string;
  /** Show cancel button */
  showCancel?: boolean;
  /** Cancel button text */
  cancelText?: string;
  /** Cancel button color */
  cancelColor?: string;
  /** Confirm button text */
  confirmText?: string;
  /** Confirm button color */
  confirmColor?: string;
  /** Show editable content */
  editable?: boolean;
  /** Placeholder for editable content */
  placeholderText?: string;
  /** Success callback */
  success?(res: { confirm: boolean; cancel: boolean; content?: string }): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

Usage Examples:

// Show toast
wx.showToast({
  title: 'Success',
  icon: 'success',
  duration: 2000
});

// Show modal
wx.showModal({
  title: 'Confirm',
  content: 'Are you sure you want to delete this item?',
  success(res) {
    if (res.confirm) {
      console.log('User confirmed');
    }
  }
});

// Navigation
wx.navigateTo({
  url: '/pages/detail/detail?id=123'
});

wx.switchTab({
  url: '/pages/home/home'
});

Media APIs

Image, video, audio, and camera operations.

interface Wx {
  /** Choose images from album or camera */
  chooseImage(options: ChooseImageOption): void;
  
  /** Choose video from album or camera */
  chooseVideo(options: ChooseVideoOption): void;
  
  /** Choose media (image/video) */
  chooseMedia(options: ChooseMediaOption): void;
  
  /** Preview images */
  previewImage(options: PreviewImageOption): void;
  
  /** Get image info */
  getImageInfo(options: GetImageInfoOption): void;
  
  /** Save image to photos album */
  saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOption): void;
  
  /** Get recorder manager */
  getRecorderManager(): RecorderManager;
  
  /** Get background audio manager */
  getBackgroundAudioManager(): BackgroundAudioManager;
  
  /** Create inner audio context */
  createInnerAudioContext(): InnerAudioContext;
  
  /** Create video context */
  createVideoContext(videoId: string, componentInstance?: any): VideoContext;
  
  /** Create camera context */
  createCameraContext(): CameraContext;
}

interface ChooseImageOption {
  /** Maximum number of images */
  count?: number;
  /** Image size type */
  sizeType?: ('original' | 'compressed')[];
  /** Image source type */
  sourceType?: ('album' | 'camera')[];
  /** Success callback */
  success?(res: { tempFilePaths: string[]; tempFiles: { path: string; size: number }[] }): void;
  /** Failure callback */
  fail?(res: any): void;
  /** Completion callback */
  complete?(res: any): void;
}

interface RecorderManager {
  /** Start recording */
  start(options: RecorderManagerStartOption): void;
  /** Pause recording */
  pause(): void;
  /** Resume recording */
  resume(): void;
  /** Stop recording */
  stop(): void;
  /** Listen for recording start */
  onStart(callback: () => void): void;
  /** Listen for recording stop */
  onStop(callback: (res: { tempFilePath: string }) => void): void;
}

Usage Examples:

// Choose and upload image
wx.chooseImage({
  count: 1,
  sizeType: ['compressed'],
  sourceType: ['album', 'camera'],
  success(res) {
    const tempFilePath = res.tempFilePaths[0];
    wx.uploadFile({
      url: 'https://api.example.com/upload',
      filePath: tempFilePath,
      name: 'image'
    });
  }
});

// Record audio
const recorder = wx.getRecorderManager();
recorder.start({
  duration: 60000,
  sampleRate: 16000,
  numberOfChannels: 1,
  encodeBitRate: 96000,
  format: 'mp3'
});

recorder.onStop((res) => {
  console.log('Recording saved:', res.tempFilePath);
});

Device APIs

System information, device capabilities, and hardware access.

interface Wx {
  /** Get system info */
  getSystemInfo(options: GetSystemInfoOption): void;
  
  /** Get system info synchronously */
  getSystemInfoSync(): SystemInfo;
  
  /** Get device info */
  getDeviceInfo(options?: GetDeviceInfoOption): void;
  
  /** Get window info */
  getWindowInfo(options?: GetWindowInfoOption): void;
  
  /** Get app base info */
  getAppBaseInfo(options?: GetAppBaseInfoOption): void;
  
  /** Get network type */
  getNetworkType(options: GetNetworkTypeOption): void;
  
  /** Listen for network status change */
  onNetworkStatusChange(callback: (res: { isConnected: boolean; networkType: string }) => void): void;
  
  /** Get clipboard data */
  getClipboardData(options: GetClipboardDataOption): void;
  
  /** Set clipboard data */
  setClipboardData(options: SetClipboardDataOption): void;
  
  /** Make phone call */
  makePhoneCall(options: MakePhoneCallOption): void;
  
  /** Scan QR/bar code */
  scanCode(options: ScanCodeOption): void;
  
  /** Set screen brightness */
  setScreenBrightness(options: SetScreenBrightnessOption): void;
  
  /** Get screen brightness */
  getScreenBrightness(options: GetScreenBrightnessOption): void;
  
  /** Set keep screen on */
  setKeepScreenOn(options: SetKeepScreenOnOption): void;
  
  /** Vibrate long */
  vibrateLong(options?: VibrateLongOption): void;
  
  /** Vibrate short */
  vibrateShort(options?: VibrateShortOption): void;
}

interface SystemInfo {
  /** Device brand */
  brand: string;
  /** Device model */
  model: string;
  /** System name */
  system: string;
  /** System version */
  version: string;
  /** Platform */
  platform: string;
  /** Language */
  language: string;
  /** WeChat version */
  version: string;
  /** SDK version */
  SDKVersion: string;
  /** Screen width in px */
  screenWidth: number;
  /** Screen height in px */
  screenHeight: number;
  /** Window width in px */
  windowWidth: number;
  /** Window height in px */
  windowHeight: number;
  /** Status bar height in px */
  statusBarHeight: number;
  /** Device pixel ratio */
  pixelRatio: number;
}

Usage Examples:

// Get system info
wx.getSystemInfo({
  success(res) {
    console.log('Device:', res.model);
    console.log('System:', res.system);
    console.log('Screen size:', res.screenWidth, 'x', res.screenHeight);
  }
});

// Scan QR code
wx.scanCode({
  success(res) {
    console.log('Scanned result:', res.result);
    console.log('Scan type:', res.scanType);
  }
});

// Set clipboard
wx.setClipboardData({
  data: 'Hello WeChat',
  success() {
    wx.showToast({ title: 'Copied to clipboard' });
  }
});

File System APIs

interface Wx {
  /** Get file system manager */
  getFileSystemManager(): FileSystemManager;
  
  /** Create offscreen canvas */
  createOffscreenCanvas(): OffscreenCanvas;
  
  /** Get performance */
  getPerformance(): Performance;
  
  /** Report performance */
  reportPerformance(id: number, value: number, dimensions?: Record<string, string>): void;
  
  /** Save file */
  saveFile(options: SaveFileOption): void;
  
  /** Get saved file list */
  getSavedFileList(options: GetSavedFileListOption): void;
  
  /** Get saved file info */
  getSavedFileInfo(options: GetSavedFileInfoOption): void;
  
  /** Remove saved file */
  removeSavedFile(options: RemoveSavedFileOption): void;
  
  /** Open document */
  openDocument(options: OpenDocumentOption): void;
}

interface FileSystemManager {
  /** Read file */
  readFile(options: ReadFileOption): void;
  /** Write file */
  writeFile(options: WriteFileOption): void;
  /** Copy file */
  copyFile(options: CopyFileOption): void;
  /** Rename file */
  rename(options: RenameOption): void;
  /** Remove file */
  unlink(options: UnlinkOption): void;
  /** Create directory */
  mkdir(options: MkdirOption): void;
  /** Remove directory */
  rmdir(options: RmdirOption): void;
  /** Read directory */
  readdir(options: ReaddirOption): void;
  /** Get file stats */
  stat(options: StatOption): void;
}

Types

// Main WeChat API interface
interface WechatMiniprogram.Wx {
  // Network APIs
  request(options: RequestOption): RequestTask;
  uploadFile(options: UploadFileOption): UploadTask;
  downloadFile(options: DownloadFileOption): DownloadTask;
  
  // Storage APIs  
  setStorage(options: SetStorageOption): void;
  getStorage(options: GetStorageOption): void;
  
  // UI APIs
  showToast(options: ShowToastOption): void;
  showModal(options: ShowModalOption): void;
  navigateTo(options: NavigateToOption): void;
  
  // Media APIs
  chooseImage(options: ChooseImageOption): void;
  chooseVideo(options: ChooseVideoOption): void;
  
  // Device APIs
  getSystemInfo(options: GetSystemInfoOption): void;
  scanCode(options: ScanCodeOption): void;
}

// Async method result type helper
type WechatMiniprogram.PromisifySuccessResult<
  P,
  T extends WechatMiniprogram.AsyncMethodOptionLike
> = P extends { success: any }
  ? void
  : P extends { fail: any }
  ? void  
  : P extends { complete: any }
  ? void
  : Promise<Parameters<Exclude<T['success'], undefined>>[0]>;

docs

ai-ml-apis.md

app-page-lifecycle.md

bluetooth-nfc-apis.md

canvas-graphics.md

cloud-services.md

component-system.md

core-apis.md

device-hardware-apis.md

event-system.md

index.md

payment-apis.md

tile.json