前提
react+TypeScriptを学習しています。
union型で定義したのですが、うまく渡すことができずに詰まっています。
実現したいこと
- union型で定義したtypesを用いて型管理を行いたい
発生している問題・エラーメッセージ
myPageSettingsの初期値に正しく型定義を反映できておらず、ユニオン型で定義した文字列以外も初期値に入力できてしまう。
該当のソースコード
型定義
ts
1//SelectType.ts 2 3export type SelectType = 'A' | 'B' | 'def'; 4
state管理
tsx
1//useGlobalState.tsx 2 3import { 4 SetStateAction, 5 createContext, 6 useContext, 7 useEffect, 8 useState, 9} from 'react'; 10import { SelectType } from '@/types/SelectType'; 11 12export const GlobalContext = createContext({ 13 selectType: 'hide' as SelectType, 14 setSelectType: (selectType: SetStateAction<SelectType>) => { 15 // dummy 16 }, 17}); 18 19export const GlobalContextProvider = ({ 20 children, 21}: { 22 children: JSX.Element | JSX.Element[]; 23}) => { 24 const context = useContext(GlobalContext); 25 26 const [selectType, setSelectType] = useState<SelectType>( 27 context.selectType 28 ); 29 30 const value = { 31 selectType, 32 setSelectType, 33 }; 34 return ( 35 <GlobalContext.Provider value={value}>{children}</GlobalContext.Provider> 36 ); 37};
該当ファイル
tsx
1//myPageSettings.tsx 2 3import router from 'next/router'; 4import { useEffect } from 'react'; 5 6import { useGlobalState } from '@/useGlobalState'; 7 8import { SelectType } from '@/types/SelectType'; 9import { AppType } from '@/types/AppType'; 10 11 12 13export const myPageSettings = ({ 14 appType = AppType.Other as AppType, 15 // 初期値と型定義を行う 該当箇所 16 selectType = 'def' as SelectType, 17}) => { 18 19 const { 20 userInfo, 21 setSelectType 22 } = useGlobalState(); 23 24useEffect(() => { 25 if (isAvailable(appType)) { 26 switch (userInfo.userType) {: 27 case "master": 28 setSelectType(selectType); 29 break; 30 default: 31 setSelectType('def'); 32 } 33 } 34 }, []); 35}; 36
試したこと
ユニオン型でなく、enum 型での定義は行えました。enumは非推奨とのことでしたので、ユニオンで定義したのですが、うまく動作できませんでした。
解決方法もしくは考え方を教えていただけると幸いです。
回答1件