gpt4 book ai didi

typescript - 如何从字符串数组构建 Typescript 类型?

转载 作者:行者123 更新时间:2023-12-02 18:55:20 25 4
gpt4 key购买 nike

到目前为止我已经有了这个。

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;
};

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

最佳答案

您可以使用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 utility type

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

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

type Themes = Record<ThemeNames, ThemeProperties>

TS Playground

关于typescript - 如何从字符串数组构建 Typescript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66236228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com