【问题标题】:Trying to dynamically set interface based off of enum value尝试根据枚举值动态设置接口
【发布时间】:2020-11-30 11:26:12
【问题描述】:
大家好,我正在尝试将样式界面动态设置为如下类型:
type IListStyles = {
[LIST_TYPE.ADD_ACTIONABLE]: IListItemAddActionableStyle;
[LIST_TYPE.SUPERVALUE]: IListItemSupervalueStyle;
}
enum LIST_TYPE {
ADD_ACTIONABLE = "ADD_ACTIONABLE",
SUPERVALUE = "SUPERVALUE",
}
export interface IListItem<T extends LIST_TYPE> {
style?: IListStyles[T];
type: T;
但我知道 T 不能用于索引 IListStyles 以前有人做过类似的事情吗?
【问题讨论】:
标签:
reactjs
typescript
react-native
types
typescript-generics
【解决方案1】:
你也可以使用一个对象来代替枚举:
const LIST_TYPE = {
ADD_ACTIONABLE: "ADD_ACTIONABLE",
SUPERVALUE: "SUPERVALUE",
} as const;
type TLISTTYPE = typeof LIST_TYPE[keyof typeof LIST_TYPE];
interface IListItemAddActionableStyle {
a: string;
}
interface IListItemSupervalueStyle {
b: string;
}
type TListStyles = {
[LIST_TYPE.ADD_ACTIONABLE]: IListItemAddActionableStyle;
[LIST_TYPE.SUPERVALUE]: IListItemSupervalueStyle;
};
export interface IListItem<T extends TLISTTYPE> {
style?: TListStyles[T];
type: T;
}
const resu: IListItem<"ADD_ACTIONABLE"> = {
type: "ADD_ACTIONABLE",
style: { a: "dskqldq" },
};
console.log({ resu });