简体   繁体   中英

How to use enum values as a type

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);

您可以只使用AudioActionTypes作为参数的类型。

const onVolumeChange = (value: number, audioActionType: AudioActionTypes) => { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM