Kevin Amiranoff
Kevin Amiranoff

Reputation: 14468

React Native extend NativeModules TypeScript types

I have a native module and I would like to type it.

Here is an example of my module's interface

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

and that is how I use it:

NativeModules.BBAudioPlayer.playSound('tada');

How can extend NativeModules to add the types of my new module?

Upvotes: 13

Views: 3948

Answers (2)

Ilia
Ilia

Reputation: 1

Extending @strdr4605 response, you also need & NativeModule or extends NativeModule to your existing interface if you want to use

new NativeEventEmitter(NativeModules.BBAudioPlayer)

Upvotes: 0

strdr4605
strdr4605

Reputation: 4352

// 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;
  }
}

enter image description here

Upvotes: 18

Related Questions