【问题标题】:TypeScript conditional types with enums带有枚举的 TypeScript 条件类型
【发布时间】:2021-09-07 09:08:36
【问题描述】:

我有以下 TypeScript 枚举:

enum UIConfigurationType {
  DisplayTableFields = "display-table-field",
  FormFields = "form-field",
  MainAttributes = "main-attribute",
  SearchAttributes = "search-attribute",
}

还有这个条件类型:

type UIConfigurationEntitySuffix<T extends UIConfigurationType> =
  T extends UIConfigurationType.DisplayTableFields
    ? "display-table-fields"
    : T extends UIConfigurationType.FormFields
    ? "form-fields"
    : T extends UIConfigurationType.MainAttributes
    ? "main-attributes"
    : T extends UIConfigurationType.SearchAttributes
    ? "search-attributes"
    : never;

例如,它应该为泛型文字类型 UIConfigurationType.SearchAttributes 静态返回文字类型 "search-attributes"(实际上它是正确的)。

然后我有下面的函数,它动态实现了前面条件类型定义的映射:

function getUIConfigurationEntitySuffix<T extends UIConfigurationType>(
  uiConfigurationType: T
): UIConfigurationEntitySuffix<T> {
  switch (uiConfigurationType) {
    case UIConfigurationType.DisplayTableFields:
      return "display-table-fields";
    case UIConfigurationType.FormFields:
      return "form-fields";
    case UIConfigurationType.MainAttributes:
      return "main-attributes";
    case UIConfigurationType.SearchAttributes:
      return "search-attributes";
    default:
      throw new Error(`Unknown uiConfigurationType: ${uiConfigurationType}`);
  }
}

此函数定义导致 TypeScript 在每个 case 分支中引发错误:

TypeScript errors on getUIConfigurationEntitySuffix function

我错过了什么?谢谢!

【问题讨论】:

    标签: typescript enums conditional-types


    【解决方案1】:

    我明白了!无论出于何种原因,TypeScript 都没有推断出返回的类型是 UIConfigurationEntitySuffix&lt;T&gt; 所期望的正确类型,所以我必须明确地转换它们:

    function getUIConfigurationEntitySuffix<T extends UIConfigurationType>(
      uiConfigurationType: T
    ): UIConfigurationEntitySuffix<T> {
      switch (uiConfigurationType) {
        case UIConfigurationType.DisplayTableFields:
          return "display-table-fields" as UIConfigurationEntitySuffix<T>;
        case UIConfigurationType.FormFields:
          return "form-fields" as UIConfigurationEntitySuffix<T>;
        case UIConfigurationType.MainAttributes:
          return "main-attributes" as UIConfigurationEntitySuffix<T>;
        case UIConfigurationType.SearchAttributes:
          return "search-attributes" as UIConfigurationEntitySuffix<T>;
        default:
          throw new Error(`Unknown uiConfigurationType: ${uiConfigurationType}`);
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2018-10-31
      • 1970-01-01
      • 2018-10-18
      • 2022-09-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      • 2019-12-30
      • 1970-01-01
      相关资源
      最近更新 更多