Trying to avoid specifying types in TypeScript and setting a value by accessing its key is causing a TypeScript error. Despite looking at multiple StackOverflow posts, I couldn't find a solution.
I encountered a similar issue with my code and tried replicating it with a sample one.
type IMyObj = {
title: string
content: string
}
type IMyObj1 = {
titles: string
content1: string
}
const myObj: IMyObj = {
title: 'Hi',
content: 'Hope all is well',
}
const myObj: IMyObj1 = {
titles: 'Hi',
content1: 'Hope all is well',
}
const myKey: string = 'content'
myObj[myKey as keyof IMyObj] = 'All is great now!' // Element implicitly has an 'any' type because expression of type 'keyof IMyObj' can't be used to index type 'IMyObj | IMyObj1'.
Property 'title' does not exist on type 'IMyObj | IMyObj1'.ts(7053) No quick fixes available
The actual code is as follows:
I need to provide a type to currentValue passed to the method, so omitting the type here is not possible.
const formatData = (
faData: FinancialSection[],
faSection: keyof FinancialSection
) => ({
..._.sortBy(
faData,
(item: FinancialSection) => item.period.year
).reduce((actualValue: any, currentValue: FinancialSection) => {
Object.keys(ProfitAndLossKeys).forEach((key: string) => {
// eslint-disable-next-line no-param-reassign
if (!actualValue[key]) actualValue[key] = { values: [] }
actualValue[key].values.push(
currentValue[faSection] && currentValue[faSection][key] !== null
? currentValue[faSection][key] //Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProfitLossData | KeyFiguresData | BalanceSheetData | CashFlowData | Period'.
No index signature with a parameter of type 'string' was found on type 'ProfitLossData | KeyFiguresData | BalanceSheetData | CashFlowData | Period'.ts(7053) : null ) }) return actualValue }, {}) })