'typescript error: Element implicitly has an 'any' type
Typescript newb here. I am getting an error on updatedState[key1].
When I hover over updatedState I get error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'classTitleObjType'. No index signature with a parameter of type 'string' was found on type 'classTitleObjType'.
and when I hover over key1 I get error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'classTitleObjType'. No index signature with a parameter of type 'string' was found on type 'classTitleObjType'.ts(7053)
With updatedState[key1] I am trying to assign a value to that key. key1 is a variable. Also updatedState is assigned classTitleObjType as its type. So doesn't updateState know the only thing type that can access it dynamically is the string 'byID' or 'allID'
interface byID {
[key: string] : {
id: string,
classTitle: string
}
}
interface classTitleObjType {
byID : byID,
allID : string[]
}
const classTitleObj: classTitleObjType = {
byID : {
"class0": {
id: "class0",
classTitle: 'PsychologyRedux'
},
"class1": {
id: "class1",
classTitle: 'HistoryRedux',
}
},
allID: ["class0", "class1"]
}
interface ADD_CLASS_ACTION {
type: 'ADD_CLASS',
payload: string
}
const classesReducer = (state: classTitleObjType = classTitleObj, action: ADD_CLASS_ACTION) => {
switch(action.type){
case 'ADD_CLASS':
let classTitleToAdd = action.payload
let updatedState: classTitleObjType = {
byID : {},
allID: []
}
for(const key1 in state){
if(Array.isArray(state[key1 as keyof classTitleObjType])){
updatedState[key1] = [...state[key1]]
} else {
updatedState[key1] = {...state[key1]}
for (const key2 in state[key1]){
updatedState[key1][key2] = {...state[key1][key2]}
}
}
}
let newNum = Object.keys(state.byID).length
let newID = "class" + newNum
updatedState.byID[newID] = {
id: newID,
classTitle: classTitleToAdd
}
updatedState.allID.push(newID)
return updatedState;
default:
return state
}
}
export default classesReducer
I thought as keyof might be the answer, but no matter what I try ([key1 as keyof classTitleObjType], [key1 as keyof state], [key1 as keyof updatedState] the error never resolves.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
