Recently, I found myself in need of a basic function to interact with native code. Rather than creating a package, I opted to create the Java files as if they were for a plugin and registered them in MainApplication.
As I'm using TypeScript, I am currently facing challenges with RN to Java interaction. I attempted to do so with a JS file like this:
import NativeModules from 'react-native';
const AndroidService = NativeModules;
export default { AndroidService }
However, I then encountered the need to define types (prompted by VS Code):
Property 'play' does not exist on type '{ AndroidService: typeof import("/home/karol/Git/TailosiveHub-react/node_modules/@types/react-native/index"); }'.
I tried creating an index.d.ts
file at the project's root, but that did not yield any results.
How can I define types for a native module in TypeScript?
MainApplication:
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new AndroidServicePackage());
// packages.add(new MainReactPackage());
return packages;
}
AndroidServicePackage:
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.<NativeModule>asList(new AndroidServiceModule(reactContext));
}
AndroidServiceModule:
@Override
public String getName() {
return "AndroidService";
}
Method:
@ReactMethod
public void play(String streamingURL/*, ReadableMap options*/) {
doSomething();
}