I am currently working on simplifying an existing interface by creating a new type. The original type is derived from @mui/x-data-grid
and is as follows:
export declare type GridEnrichedColDef<R extends GridValidRowModel = any, V = any, F = V> = GridColDef<R, V, F> | GridActionsColDef<R, V, F>;
The properties that I want to include in the new type are:
export type SupportedColumnProps =
| 'field'
| 'headerName'
| 'width'
| 'renderCell'
| 'valueFormatter'
| 'flex'
| 'sortable'
| 'hide'
| 'type'
| 'cellClassName';
In addition, I want to support the getActions
property if the type
property is set to 'actions'
. However, I am facing an issue in defining the type to recognize that it should allow getActions
only when the type
is set to 'actions'
.
How can I simplify the interface and provide default values for this new type?
Thank you!
Update 1/30/2023
Based on @Oblosys's response, I have updated the type definition as follows:
export type SupportedColumnProps =
| 'field'
| 'headerName'
| 'width'
| 'renderCell'
| 'renderHeader'
| 'valueFormatter'
| 'flex'
| 'sortable'
| 'hide'
| 'type'
| 'cellClassName'
| 'editable'
| 'getActions'
| 'valueOptions';
// Reference: https://stackoverflow.com/questions/75271774/creating-a-type-using-pick-with-a-type-that-is-defined-as-a-union-of-types/75290368#75290368
type KeyOfUnion<T> = T extends unknown ? keyof T : never;
type PickUnion<T, K extends KeyOfUnion<T>> = T extends unknown
? K & keyof T extends never
? never
: Pick<T, K>
: never;
export type GridColumn = PickUnion<GridEnrichedColDef, SupportedColumnProps> & { enableColumnMenu?: boolean };
However, I am now encountering an issue where if I define a column without the type
or getActions
properties, it does not satisfy the defined type. For example:
const column: GridColumn = {
field: 'hello'
}