问题描述
嘿,我正在尝试将样式界面动态设置为如下类型:
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;
Buuut,我知道T不能用于索引IListStyles
,以前有人做过这样的事吗?
解决方法
您还可以使用对象代替枚举:
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 });