I have this React code. if ( !Object.values(eventsList).includes(eventType) &&…
- User
I have this React code. if ( !Object.values(eventsList).includes(eventType) && !Object.values(eventsFromIframe).includes(eventType) ) { throw new Error(
eventType ${eventType} not supported); } The types are: /** ws события из iframe / export const eventsFromIframe = { /* Оправка нового сообщения оператору (для Арм и СРМ) / newMessage: 'newMessageWs', /* Уведомление с информацией об удержании обращения / appealRetention: 'appealRetentionWs', /* Уведомление о закрытии обращения / appealClose: 'appealCloseWs', /* Уведомление при трансфере обращения иззвне / transferAppeal: 'transferAppealWs', /* Уведомдение о скором уходе обращния в ожидание / appealSoonToWaiting: 'appealSoonToWaitingWs', /* Уведомление при ужоде обращения в ожидании извне / appealToWait: 'appealToWaitWs', /* Нотификация об изменении статуса оператора / userStatusChanged: 'userStatusChangedWs', /* Нотификация о тайпинге клиента / clientTyping: 'clientTypingWs', /* Нотификация о проставлении оценки / csiRate: 'csiRateWs', /* Нотификация об изменении заметочной информации */ remarkInfoChanged: 'remarkInfoChangedWs', } as const; export type TIframeWsEvents = (typeof eventsFromIframe)[keyof typeof eventsFromIframe];/** Список событий / export const eventsList = { /* Нотификация о новом обращении (для СРМ) / newAppeal: 'newAppeal', /* Оправка нового сообщения оператору (для Арм и СРМ) / newMessage: 'newMessage', /* Уведомление с информацией об удержании обращения / appealRetention: 'appealRetention', /* Уведомление о закрытии обращения / appealClose: 'appealClose', /* Уведомление при трансфере обращения иззвне / transferAppeal: 'transferAppeal', /* Уведомдение о скором уходе обращния в ожидание / appealSoonToWaiting: 'appealSoonToWaiting', /* Уведомление при ужоде обращения в ожидании извне / appealToWait: 'appealToWait', /* Нотификация об изменении статуса оператора / userStatusChanged: 'userStatusChanged', /* Нотификация о тайпинге клиента / clientTyping: 'clientTyping', /* Нотификация о проставлении оценки / csiRate: 'csiRate', /* Нотификация об изменении заметочной информации / notForWaiting: 'notForWaiting', /* Нотификация об изменении заметочной информации / remarkInfoChanged: 'remarkInfoChanged', /* Нотификация об изменении комментария к обращению / appealCommentChanged: 'appealCommentChanged', /* Нотификция об изменении тематик обращения */ appealThemesChanged: 'appealThemesChanged', setActiveAppeal: 'setActiveAppeal', } as const;
/** Тип описывающий возможные варианты событий */ export type TEvents = (typeof eventsList)[keyof typeof eventsList]; on eventType I get a typeScript error 'Argument of type 'TEvents | TIframeWsEvents' is not assignable to parameter of type '"newAppeal" | "newMessage" | "appealRetention" | "appealClose" | "transferAppeal" | "appealSoonToWaiting" | "appealToWait" | "userStatusChanged" | "clientTyping" | "csiRate" | ... 4 more ... | "setActiveAppeal"'. Type '"newMessageWs"' is not assignable to type '"newAppeal" | "newMessage" | "appealRetention" | "appealClose" | "transferAppeal" | "appealSoonToWaiting" | "appealToWait" | "userStatusChanged" | "clientTyping" | "csiRate" | ... 4 more ... | "setActiveAppeal"'. Did you mean '"newMessage"'?'
- Assistant
The error is occurring because the
eventTypevariable is expected to have a specific set of values defined by the union typeTEvents. However, theeventsFromIframeobject contains values that are not included in theeventsListobject, causing TypeScript to throw the error.To fix this issue, you can create a union type that includes all the values from both
eventsListandeventsFromIframe. Then you can use this new union type as the type for theeventTypevariable.Here is how you can do it:
// Define a new union type that includes values from both eventsList and eventsFromIframe type TAllEvents = TEvents | TIframeWsEvents; // Update the check to use the TAllEvents type if ( !Object.values(eventsList).includes(eventType as TAllEvents) && !Object.values(eventsFromIframe).includes(eventType as TAllEvents) ) { throw new Error(`eventType ${eventType} not supported`); }By creating a new union type
TAllEventsthat includes all values from botheventsListandeventsFromIframe, TypeScript will now allow to have values from either of the two objects. And by using type assertion , you can resolve the TypeScript error. - User
Why can't typescript do this without creating specific type here?
- Assistant
TypeScript is designed to provide static type checking to prevent potential runtime errors and improve code quality. In this case, TypeScript is enforcing type safety by checking that the
eventTypevariable is limited to a specific set of values defined by the union typeTEvents.When you are performing checks like
!Object.values(eventsList).includes(eventType)in your code, TypeScript needs to ensure that theeventTypevariable is compatible with the expected types. SinceeventTypecan potentially have values from botheventsListandeventsFromIframe, TypeScript is unable to infer the specific type without explicit guidance.By creating a new union type
TAllEventsthat includes values from botheventsListandeventsFromIframe, you are providing TypeScript with a clear definition of the possible values thateventTypecan have. This helps TypeScript accurately check the type compatibility and prevent unexpected errors at runtime.While it may seem inconvenient to define an additional type in this scenario, it is a way to ensure type safety and maintain consistency in your code. It also helps TypeScript to accurately verify the types and prevent potential bugs.