是否可以在 TypeScript 上创建一个允许灵活 number/type 键的对象接口?

Is it possible to create an object interface on TypeScript that allows a flexible number/type of keys?

在为 React 组件创建主题时,我想知道定义对象类型的最佳方式是什么。基本上我有一个反应组件,它接受一个样式对象来创建一个主题。如下图:

const datePickerTheme = {
    palette: {
        primary: "#f5f5f5",
        secondary: "#2b4450",
        tertiary: "#871111"
    },
    spacing: ["0px", "4px", "8px", "16px", "32px", "64px"],
};

它将像这样传递到日期选择器组件:

<DatePicker theme={datePickerTheme}/>

在打字稿上它有一个像这样的接口:

interface ITheme {
  palette: {
    primary: string,
    secondary?: string,
    tertiary?: string,
  },
  spacing: [],
}

但是,我想保持界面开放,以便将来为其他可能性定制主题。基本上,一个人应该能够通过任何类型的主题,无论需要多少键。有没有一种方法可以定义接口,使其在不使用类型“theme:any”的情况下灵活开放。

这是你想要的吗?您可以在 palette 对象中添加任何键。

interface ITheme {
  palette: {
    primary: string,
    secondary: string,
    tertiary: string,
    [key: string]: string
  },
  spacing: [],
}

或者您可以通过提供 type.

来限制键的值
type PaletteKey = 'third' | 'fourth';

interface ITheme {
  palette: {
    primary: string,
    secondary: string,
    tertiary: string,
    [key: PaletteKey]: string
  },
  spacing: [],
}

已编辑

为了将来基于ITheme的自定义,您可以扩展接口。

例如:

interface IPalette {
  primary: string;
  secondary: string;
  tertiary: string;
}

interface ITheme {
  palette: IPalette;
  spacing: [];
}

type Breakpoints = {
  xs: number;
  sm: number;
  md: number;
  lg: number;
  xl: number;
};

interface CustomTheme extends ITheme {
  palette: IPalette & {
    error: string;
    success: string;
  };
  breakpoints: Breakpoints;
}