I have been trying to get the specific type based on an function argument but I can't find any way in typescript.
This "step" argument is actually a key in the slice
type Slice1 = {
info: string
}
type Slice2 = {
info: string
}
type MyAppState = {
step1: Slice1;
step2: Slice2;
}
function useStep<T>(step: keyof T): T[typeof step] {
const [state] = useContext(ExternalContext);
return state[step];
}
const step1 = useStep<MyAppState>('step1'); <-- **should return Slice1 type**
I want to get the correct type depending on the key.
MyAppStateto theuseStepfunction? The solution is probably to use<T extends keyof MyAppState>(step: T): MyAppState[T]but I'm not sure what your goal is.keyof T, so that your return type can be based on this specific key. In the unlikely case thatExternalContextcan have multiple types of state, you can make both the state and the key generic like sofunction useStep<T, K extends keyof T>(step: K): T[K], but you would no longer be able to specify T without also specifying K, so you couldn't typeuseStep<MyAppState>('step1'). If the only possible type of state isMyAppStatethen only the key needs to be generic and it will be what the others have said.