簡體   English   中英

如何在 Typescript 中定義具有一些可選指定屬性以及一些必需指定屬性的類型

[英]How to define a type with some optional specified properties along side some required specified ones in Typescript

我有以下 object:

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設置為可選屬性,但它們的rest保持不變?

由於shadeKey值是已知且有限的,您可以將它們寫為屬性而不是索引簽名:

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

在這里? dark30light30之后表明該屬性是可選的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM