'Cannot access a state object by key in typescript?
I want to be able to access a state object I set the interfaces for that manner but I am still getting the error for some reason could you please explain what is happening ? and how to solve it , i am getting
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'stateInterface'. the Erorr is showing on selected[target]
interface List {
name: string;
id: string;
}
interface stateInterface {
name: string | keyof List;
id: string | keyof List;
}
const initialState: stateInterface = {
name: '',
id: '',
};
const [selected, setSelected] = useState(initialState);
const returnValueOnCondition = (e: React.FocusEvent<HTMLInputElement>) => {
const target = e.currentTarget.name; // target will return name or id
if (foucusedRef.current && selected[target] === '') foucusedRef.current = false;
};
<TextField
autoComplete='off'
name='name'
value={selected.name}
onBlur={returnValueOnCondition}
/>
<TextField
autoComplete='off'
name='id'
value={selected.name}
onBlur={returnValueOnCondition}
/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|