首页 > 解决方案 > 如何从字符串数组构建 Typescript 类型?

问题描述

到目前为止,我有这个。

export const PacerThemes = ['Default', 'Dark Muted', 'Neon'] as const;
export type PacerTheme = typeof PacerThemes[number];

type ThemeProperties = {
  exhaleHoldBorderColor: string;
  exhaleHoldColor: string;
  inhaleHoldBorderColor: string;
  inhaleHoldColor: string;
};

type Themes = {
  Default: ThemeProperties;
  'Dark Muted': ThemeProperties;
  Neon: ThemeProperties;
};

有没有办法从数组生成Themes类型?PacerThemes

标签: typescripttypescript-typings

解决方案


正如评论中所建议的,您可以使用Mapped type

    type ThemeNames = "Default" | "Dark Muted" | "Neon";

    type ThemeProperties = {
      exhaleHoldBorderColor: string;
      exhaleHoldColor: string;
      inhaleHoldBorderColor: string;
      inhaleHoldColor: string;
    };

    type Themes = {
      [T in ThemeNames]: ThemeProperties;
    };

或者您可以使用Record 实用程序类型

    type ThemeNames = "Default" | "Dark Muted" | "Neon";

    type ThemeProperties = {
      exhaleHoldBorderColor: string;
      exhaleHoldColor: string;
      inhaleHoldBorderColor: string;
      inhaleHoldColor: string;
    }

    type Themes = Record<ThemeNames, ThemeProperties>

TS游乐场


推荐阅读