1

我的目标是在接口 TypeScript 中编写所有内容。它适用于 React Native。

这是我无法放入界面的功能。当前的解决方案是将其放在界面之外,但导入会很丑陋,例如 import AudioRecorderModule, { addAudioRecorderEventListener } from '...'

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

录音机.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;

录音机.d.ts

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

1 回答 1

0

我很困惑你为什么要从.d.ts. 您应该将您的界面放在.ts文件中,并在您编写代码.d.ts时生成界面build

为了调用new NativeEventEmitter(AudioRecorderModule),模块必须实现EventSubscriptionVendor接口。

我认为这段代码回答了你的问题:

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;

但请注意,当我们使用 时as AudioRecorderInterface & EventSubscriptionVendor,我们是在告诉 typescript 模块必须实现这些接口。如果模块实际上没有实现这些方法,您将遇到问题。

于 2021-02-03T01:42:04.803 回答