Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define variable with generic type argument?

Consider the following code to define a React component with a generic type argument TRow:

function DataTable<TRow> ({ rows: TRow[] }) {
  return (
  )
}

In previous code, ES6 was used and components were defined as stateless functions:

const DataTable = ({ rows }) => ( ... )

How can I define such a function so that it has a generic type argument TRow? Is this supported by Typescript at all?

like image 606
Bob van der Linden Avatar asked Oct 21 '25 16:10

Bob van der Linden


1 Answers

Yes it is possible, but only for Functions, not any arbitrary variable. As you can see, it's the type itself, where you define generics and then you can make a variable of that type, which allows it to set the generic.

These all are equivalent:

interface Row { a: number }

function DataTable1<T>({ rows }: { rows: T[] }): void { return void 0 }
const DataTable2: <T>({ rows }: { rows: T[] }) => void = ({rows}) => void 0
type  DataTable = <T>({ rows }: { rows: T[] }) => void
const DataTable3: DataTable = ({rows}) => void 0

const a1 = DataTable1<Row>({rows: [{a: 1}]})
const a2 = DataTable2<Row>({rows: [{a: 2}]})
const a3 = DataTable3<Row>({rows: [{a: 3}]})
like image 99
Qwerty Avatar answered Oct 23 '25 13:10

Qwerty