I have an enum
export enum AudioActionTypes {
UpdateMusicData = 'UPDATE_MUSIC_DATA',
UpdateVoiceData = 'UPDATE_VOICE_DATA',
UpdateSoundData = 'UPDATE_SOUND_DATA',
}
And a function that is dispatching an event to update the global context.
const onVolumeChange = (value: number, audioActionType: AudioActionTypes[keyof typeof AudioActionTypes]) => {
audioDispatch({
type: audioActionType,
payload: { volume: value / 100 },
});
};
I want to make typescript understand that I am passing only the AudioActionTypes.
If I am setting the type for audioType
to be the enum itself ( AudioActionTypes )
( audioActionType: AudioActionTypes
)
typescript complains and throws this error.
Argument of type '{ type: AudioActionTypes; payload: { volume: number; }; }' is not assignable to parameter of type 'AudioActions'.
Type '{ type: AudioActionTypes; payload: { volume: number; }; }' is not assignable to type '{ type: AudioActionTypes.UpdateSoundData; payload: ISoundSettings; }'.
Types of property 'type' are incompatible.
Type 'AudioActionTypes' is not assignable to type 'AudioActionTypes.UpdateSoundData'.
audioDispatch has this types.
type AudioActions = {
type: AudioActionTypes.UpdateMusicData;
payload: IMusicSettings;
} | {
type: AudioActionTypes.UpdateVoiceData;
payload: IVoiceSettings;
} | {
type: AudioActionTypes.UpdateSoundData;
payload: ISoundSettings;
}
const audioDispatch: React.Dispatch<AudioActions>;
How should I manage the types for the audioActionType parameter so I can call the function with this argument and don't have any type error?
onVolumeChange(4, AudioActionTypes.UpdateVoiceData);