代码之家  ›  专栏  ›  技术社区  ›  Gadzhiev Islam

在typescript中如何将接口键声明为特定类型?

  •  0
  • Gadzhiev Islam  · 技术社区  · 6 月前

    我有界面:

    export type TCategoryAnalyzes = {
      categoryId: string,
      analyzes: IAnalyzesStorageData[],
      region: string,
    };
    

    目标是使其类似于:

    export type TCategoryAnalyzes = {
      region: { // string
        categoryId: string,
        analyzes: IAnalyzesStorageData[],
      }
    };
    

    在哪里 region 密钥必须是 string 类型

    1 回复  |  直到 6 月前
        1
  •  1
  •   Medali Landolsi    6 月前
    export type TCategoryAnalyzes = {
      [region: string]: {
        categoryId: string;
        analyzes: IAnalyzesStorageData[];
      };
    };
    

    这就是你实现它的方法。

        2
  •  0
  •   bpeter340    6 月前
    export type TCategoryAnalyzes = Record<string, {
      categoryId: string;
      analyzes: IAnalyzesStorageData[];
    }>;
    

    这也可能适用于您的用例。然而 Record utility type 可能不如原始答案灵活。