React Native utöka NativeModules TypeScript-typer


Jag har en inbyggd modul och jag skulle vilja skriva den.

Här är ett exempel på gränssnittet för min modul

export interface BBAudioPlayer {
  playSound: (sound: 'click' | 'tada') => Promise<void>;
  pause: () => Promise<void>;
}

och det är så jag använder det:

NativeModules.BBAudioPlayer.playSound('tada');

Hur kan jag utöka NativeModules för att lägga till typerna för min nya modul?

Svar #1

// extendNativeModules.d.ts
// import original module declarations
import 'react-native';

export interface BBAudioPlayerInterface {
  playSound: (sound: 'click' | 'tada') => Promise<void>;
  pause: () => Promise<void>;
}

// and extend them!
declare module 'react-native' {

  interface NativeModulesStatic {
    BBAudioPlayer: BBAudioPlayerInterface;
  }
}

Relaterade artiklar