【问题标题】:Recursive types with typescript带有打字稿的递归类型
【发布时间】: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


【解决方案1】:

您需要在 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);

【讨论】:

    猜你喜欢
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2021-06-30
    • 2022-11-10
    • 2021-10-23
    • 2021-12-15
    • 2021-12-19
    相关资源
    最近更新 更多