【问题标题】:How to define a type with some optional specified properties along side some required specified ones in Typescript如何在 Typescript 中定义具有一些可选指定属性以及一些必需指定属性的类型
【发布时间】:2021-08-28 05:36:26
【问题描述】:

我有以下对象:

const colors: tColors = {
  dark: {
     main: {
       normal: '#022c43', dark30: '#011f2f', light30: '#4e6b7b', contrastColor: '#fff',
     },
     secound: {
       normal: '#053f5e', dark30: '#042c42', light30: '#add6de', contrastColor: '#fff',
     },
     error: { normal: '#d32f2f', contrastColor: '#fff' },
     success: { normal: '#388e3c', contrastColor: '#fff' },
  },
  light: {
     main: {
       normal: '#28527a', dark30: '#1c3955', light30: '#6986a2', contrastColor: '#fff',
     },
     secound: {
       normal: '#8AC4D0', dark30: '#618992', light30: '#50798e', contrastColor: '#fff',
     },
     error: { normal: '#e57373', contrastColor: '#000' },
     success: { normal: '#81c784', contrastColor: '#000' },
  },
};

我将tColors定义为:

type tColors = {
  [themeKey in 'light' | 'dark']: {
    [key : string]: {
       [shadeKey: string ]: string
    }
  }
};

它有效,但如果我想像这样限制shadeKey

shadekey in 'normal' | 'dark30' | 'light30' | 'contrastColor'

它在errorsuccess 字段上给了我一些错误,错误是:

Type '{ normal: string; contrastColor: string; }' is missing the following properties from type '{ normal: string; dark30: string; light30: string; contrastColor: string; }': dark30, light30

问题是我不想在errorsuccess 字段中添加dark30light30,但我希望shadekey 对其他键敏感

有什么方法可以将dark30light30 设置为可选属性,但其余属性保持不变?

【问题讨论】:

  • 然后将其设为可选:[shadeKey in 'normal' | 'dark30' | 'light30' | 'contrastColor']?: string

标签: typescript types typescript-typings


【解决方案1】:

由于shadeKey 值是已知且有限的,您可以将它们写为属性而不是索引签名:

type tColors = {
  [themeKey in "light" | "dark"]: {
    [key: string]: {
      normal: string;
      dark30?: string;
      light30?: string;
      contrastColor: string;
    };
  };
};

这里?dark30light30 之后表明该属性是可选的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-31
    • 2021-05-08
    • 2022-08-16
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多