【发布时间】:2021-07-10 23:10:19
【问题描述】:
我想创建一个类型,它是一个包含字符串的对象或包含字符串或对象的对象,...
所以我所做的就是创建一个这样的类型:
type TranslationObject = { [key: string]: string | TranslationObject };
但是在reduce中使用它时,这就是导致错误的地方
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);
错误是
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'.
所以我的类型要么是字符串类型,要么是对象类型,但在这种情况下,我希望它是对象部分,但我无法真正弄清楚。
【问题讨论】:
-
您是否需要在
acc[translationKey]之后添加as TranslationObject,这样您就不会尝试使用字符串键来索引可能是字符串的内容?所以((acc[translationKey] as TranslationObject)[namespace] as TranslationObject)在问题行?
标签: javascript typescript reduce