typescript - 如何从字符串数组构建 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
解决方案
正如评论中所建议的,您可以使用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>
推荐阅读
- javascript - 外部 JS 文件引擎——使用 node.js 操作数据库?php?
- amazon-web-services - Serverless 通过层次结构路径获取 SSM 参数
- corda - Corda - 持久状态 V/S 线性状态
- android - 如何不根据大小将下载的图像正确显示到警报对话框中?
- javascript - 更改传单上图标的质量
- flutter - 我们如何删除某些目录中的文件?
- c - 从链表计算数据并将结果输出到 C 中的 CSV 文件
- html - 缩小窗口时如何摆脱水平滚动条?
- node.js - 无法连接到 MongoDB 服务器
- html - 超过 6 种不同颜色代码的字体大小