Here is a challenge...
This is the code snippet from titleBarContainer.tsx:
function TitleBarContainer() {
const systemData = useSelector((state: RootState) => state.counter.systemData)
const dispatch = useDispatch()
const onChangeSystemData = useCallback(
(key: keyof SystemState, value: SystemStateType) => {
let tempSystemData = Object.assign({}, systemData)
tempSystemData[key] = value // It's not working as expected, but that's not the main issue.
dispatch(changeSystemData(tempSystemData))
},
[dispatch, systemData]
)
}
This is the content of system.d.ts file:
interface SystemState {
title: TitleStateType
windowState: WindowStateType
language: LanguageStateType
mode: ModeStateType
}
type TitleStateType = string
type LanguageStateType = 'ko-KR' | 'en-US'
type WindowStateType = 'normal' | 'minimize' | 'maximize' | 'fullscreen'
type ModeStateType = 'admin' | 'user'
type SystemStateType = TitleStateType | WindowStateType | LanguageStateType | ModeStateType
Within the onChangeSystemData Function, I would like to have a specific type for 'value'.
For instance, if 'key' is 'normal', I expect 'value' to be of type WindowStateType rather than SystemStateType.
I attempted to use generic types. Below is the approach I tried:
Prior version of titleBarContainer.tsx (which did not work):
function TitleBarContainer() {
const systemData = useSelector((state: RootState) => state.counter.systemData)
const dispatch = useDispatch()
const onChangeSystemData<SystemState> = (key, value) => {
let tempSystemData = Object.assign({}, systemData)
tempSystemData[key] = value
dispatch(changeSystemData(tempSystemData))
}
}
Prior version of system.d.ts:
interface SystemState {
title: TitleStateType
windowState: WindowStateType
language: LanguageStateType
mode: ModeStateType
}
type TitleStateType = string
type LanguageStateType = 'ko-KR' | 'en-US'
type WindowStateType = 'normal' | 'minimize' | 'maximize' | 'fullscreen'
type ModeStateType = 'admin' | 'user'
type SystemStateType = TitleStateType | WindowStateType | LanguageStateType | ModeStateType
interface InternalState<T> { (key: keyof T, value: T[keyof T]): void }
It seems quite complex to me... Any suggestions or solutions would be greatly appreciated.