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?
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}]})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With