简体   繁体   English

如何使用枚举值作为类型

[英]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.我想让打字稿明白我只传递了 AudioActionTypes。 If I am setting the type for audioType to be the enum itself ( AudioActionTypes ) ( audioActionType: AudioActionTypes ) typescript complains and throws this error.如果我将audioType的类型设置为枚举本身( AudioActionTypes )( audioActionType: AudioActionTypes ),打字稿会抱怨并抛出此错误。

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. audioDispatch有这种类型。

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?我应该如何管理 audioActionType 参数的类型,以便我可以使用此参数调用函数并且没有任何类型错误?

onVolumeChange(4, AudioActionTypes.UpdateVoiceData); onVolumeChange(4, AudioActionTypes.UpdateVoiceData);

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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