Skip to content

faustienf/component-with-generic

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 

Repository files navigation


Define base types

type Row = Record<string, string>

type Column = {
  id: keyof Row;
  title: string;
}

type Props<C extends Column, R extends Row> = {
  columns: C[];
  rows: R[];
  onSelect: (row: R) => void;
}

Pass generics into Props

export const Table = <C extends Column, R extends Row>(props: Props<C, R>) => {
  ...
};

Define domain types

type User = {
  id: string;
  firstName: string;
  lastName: string;
}

type UserColumn = {
  id: keyof User;
  title: string;
}

declare const userColumns: UserColumn[];
declare const users: User[];

Pass domain props

<Table<UserColumn, User>
  columns={userColumns}
  rows={users}
  onSelect={(user/* infered User type */) => {}}
/>

or

<Table
  columns={userColumns}
  rows={users}
  onSelect={(user/* infered User type */) => {}}
/>