Влад
Влад

Reputation: 27

TS types for rows in custom re-usable table component

I'm creating re-usable component, but not sure how I can specify type for rows.

const CustomTable = ({ columns, rows, actions }: TablePropsTypes) => {}

Types:

export interface IColumn {
    field: string;
    fieldName: string;
    fieldType: 'number' | 'string';
    editable?: boolean;
}

export interface IColumns extends Array<IColumn> {}

export type TablePropsTypes = {
    columns: IColumns;
    rows: Array<Object>; // Not sure how to add here a type if user can pass different data here
    actions: boolean;
}

Upvotes: 1

Views: 35

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250336

Probably your best choice is to make the component generic. This allows yo to capture the call site type, and offer validation for the field property:

const CustomTable = <T,>({ columns, rows, actions }: TablePropsTypes<T>) => {
    return <></>
}

export interface IColumn<T> {
    field: keyof T;
    fieldName: string;
    fieldType: 'number' | 'string';
    editable?: boolean;
}

export interface IColumns<T> extends Array<IColumn<T>> {}

export type TablePropsTypes<T> = {
    columns: IColumns<T>;
    rows: Array<T>; 
    actions: boolean;
}

const data = [{ name: "", value: 0}]
let t = <CustomTable actions={true} rows={data} columns={[
    { field: "name", fieldName: "Name", fieldType: "string" }
]} />

let terr = <CustomTable actions={true} rows={data} columns={[
    { field: "name2", fieldName: "Name", fieldType: "string" }
]} />

Playground Link

Upvotes: 1

Related Questions