How to rewrite this function to a interface?

Viewed 113

My goal is to write everything in interface, TypeScript. It's for React Native.

This is the function I am unable to put into an interface. The current solution is to put it outside the interface but the import would be ugly e.g import AudioRecorderModule, { addAudioRecorderEventListener } from '...'

export const addAudioRecorderEventListener = (
  listener: (data: number[]) => void,
) => eventEmitter.addListener('read', listener);

AudioRecorder.module.ts

import {NativeEventEmitter, NativeModules} from 'react-native';

import AudioRecorderInterface from './AudioRecorder.d';

const {AudioRecorderModule} = NativeModules;

const eventEmitter = new NativeEventEmitter(AudioRecorderModule);

export const addAudioRecorderEventListener = (
  listener: (data: number[]) => void,
) => eventEmitter.addListener('read', listener);

export default AudioRecorderModule as AudioRecorderInterface;

AudioRecorder.d.ts

export default interface AudioRecorderInterface {
  startAudioRecordingAsync(): Promise<null>;
  stopAudioRecordingAsync(): Promise<null>;
}
1 Answers

I'm confused as to why you are importing from a .d.ts. You should put your interface in the .ts file and let the the .d.ts be generated when you build your code.

In order to call new NativeEventEmitter(AudioRecorderModule), the module has to implement the EventSubscriptionVendor interface.

I think this code answers your question:

interface AudioRecorderInterface {
  startAudioRecordingAsync(): Promise<null>;
  stopAudioRecordingAsync(): Promise<null>;
  addAudioRecorderEventListener(listener: (data: number[]) => void): EmitterSubscription;
}

const AudioRecorderModule = NativeModules.AudioRecorderModule as AudioRecorderInterface & EventSubscriptionVendor;

const eventEmitter = new NativeEventEmitter(AudioRecorderModule);

AudioRecorderModule.addAudioRecorderEventListener = (
  listener: (data: number[]) => void,
) => eventEmitter.addListener('read', listener);

export default AudioRecorderModule;

But be aware that when we use as AudioRecorderInterface & EventSubscriptionVendor, we are telling typescript that the module must implement those interfaces. You will have problems if the module doesn't actually implement those methods.

Related