14

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?

2 Answers 2

20
// 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

Sign up to request clarification or add additional context in comments.

1 Comment

ah awesome. thanks! One of the issues I had is, I had called the file index.d.ts inside my folder and it didn't get picked up. Renaming the file to something else worked.
0

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

new NativeEventEmitter(NativeModules.BBAudioPlayer)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.