I'm looking to define a type that can hold either a string or an object containing a string or another object...
To achieve this, I came up with the following type definition:
type TranslationObject = { [key: string]: string | TranslationObject };
However, when using this type within a reduce function, it throws an error.
Object.keys(newTranslations).reduce((acc: TranslationObject, translationKey: string): TranslationObject => {
return {
...acc,
[translationKey]: {
...acc[translationKey] as TranslationObject,
[namespace]: {
...(acc[translationKey][namespace] as TranslationObject), // Error at this line
...newTranslations
}
}
}
}, translations);
The specific error message is:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'string | TranslationObject'. No index signature with a parameter of type 'string' was found on type 'string | TranslationObject'.
It seems like my type is being inferred as either a string or an object, but I need it to always be treated as an object and I'm struggling to resolve this issue.