[英]Is it possible to create an object interface on TypeScript that allows a flexible number/type of keys?
On creating a theme for a React component I was wondering what the best way to define an object type would be.在为 React 组件创建主题时,我想知道定义 object 类型的最佳方法是什么。 Basically I have a react component that takes in a style object to create a theme.
基本上我有一个反应组件,它采用 object 风格来创建主题。 Such as below:
比如下图:
const datePickerTheme = {
palette: {
primary: "#f5f5f5",
secondary: "#2b4450",
tertiary: "#871111"
},
spacing: ["0px", "4px", "8px", "16px", "32px", "64px"],
};
it would be passed in to a datepicker component like so:它将像这样传递给 datepicker 组件:
<DatePicker theme={datePickerTheme}/>
On type script it has an interface like so:在类型脚本上,它具有如下界面:
interface ITheme {
palette: {
primary: string,
secondary?: string,
tertiary?: string,
},
spacing: [],
}
However, I would like keep the interface open for future theme customizations for other possibilities.但是,我希望保持界面开放,以便将来进行主题自定义以实现其他可能性。 Basically one should be able to pass a theme of any kind and however many keys needed.
基本上,一个人应该能够传递任何类型的主题,无论需要多少键。 Is there a way to define the interface so that it is flexible and open for such cases without using type "theme:any".
有没有办法定义接口,以便在不使用“主题:任何”类型的情况下灵活和开放。
Is this what you want?这是你想要的吗? You can add any key in
palette
object.您可以在
palette
object 中添加任何键。
interface ITheme {
palette: {
primary: string,
secondary: string,
tertiary: string,
[key: string]: string
},
spacing: [],
}
Or you can restrict the value of key by provide a type
.或者您可以通过提供
type
来限制 key 的值。
type PaletteKey = 'third' | 'fourth';
interface ITheme {
palette: {
primary: string,
secondary: string,
tertiary: string,
[key: PaletteKey]: string
},
spacing: [],
}
For future customizations base on the ITheme
, you can extend the interface.对于基于
ITheme
的未来自定义,您可以扩展接口。
For example:例如:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.