带有打字稿的递归类型

时间:2021-04-15 21:56:26

标签: javascript typescript reduce

我想创建一个类型,它是一个包含字符串的对象或一个包含字符串或对象的对象,...

所以我所做的是创建一个这样的类型:

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'.

所以我的类型要么是一个字符串,要么是一个对象,但在那种情况下,我希望它是对象部分,但我真的无法弄清楚。

1 个答案:

答案 0 :(得分:0)

您需要在 acc[translationKey] 之后添加为 TranslationObject,因为您无法尝试从字符串中获取密钥。

Object.keys(newTranslations).reduce((acc: TranslationObject, translationKey: string): TranslationObject => {
    return {
      ...acc,
      [translationKey]: {
        ...acc[translationKey] as TranslationObject,
        [namespace]: {
          ...((acc[translationKey] as TranslationObject)[namespace] as TranslationObject), 
          ...newTranslations
        }
      }
    }
  }, translations);