I'm trying to pass a string index to use on one of two state types. It throws the following error:
type Index = 'name' | 'length' | 'width' | 'depth' | 'height'
interface StateOne {
name: string
length: number
}
interface StateTwo {
width: number
depth: number
height: number
}
interface SwitchProps {
state: StateOne | StateTwo
index: Index
}
function testFunction({state, index}: SwitchProps) {
const test = state[index]
}
//TS7053: Element implicitly has an 'any' type because expression of type 'Index' can't be used to index type 'StateOne | StateTwo'.
//Property 'name' does not exist on type 'StateOne | StateTwo'.
How would you write this to get around the problem?
This works, but it is a bad workaround:
const test = state[index as unknown as keyof typeof state]
state[index].namelooks wrong.'name'would be passed throughindex, no?