Typescript:如果存在另一个道具,则强制泛型T具有某些属性



我有一个表组件,它有这样的道具:

type TableProps<T extends object> = {
columns: Column<T>[];
data: T[];
expandable?: boolean;
};

我想这样做,如果expandable道具被提供/设置为true,它会强制使用T extends {details: ReactNode}而不是T extends object,因为细节节点是我在扩展行时想要渲染的。

以这种方式使用泛型可能吗?

我的建议是使用三元条件类型。你可以在这里找到更多

下面是我建议你做的方法

type TablePropsCommonProperties<T> = {
columns: Column<T>[];
data: T[];
};
type TablePropsDetails<T extends { details: ReactNode }> = {
expandable: true;
} & TablePropsCommonProperties<T>;
type TablePropsWithoutDetails<T extends object> = {
expandable: false;
} & TablePropsCommonProperties<T>;
type TableProps<T extends object> = T extends { details: ReactNode } ? TablePropsDetails<T> : TablePropsWithoutDetails<T>;
/* Valid */
const validWithDetails: TableProps<{ details: ReactNode }> = {
expandable: true,
columns: ['test'],
data: [{ details: <></> }]
}
/* Not Valid, expandable can't be true if details is not provided */
const notValidDithDetails: TableProps<{ prop: string }> = {
expandable: true,
columns: ['test'],
data: [{ prop: 'my prop' }]
}

希望它能帮助你🚀

最新更新