How to use generic in Typescript tuple

101 Views Asked by At

I'm trying to create the correct signature of toTableGeneric function. It should take an array of Column, where the second generic can vary for each array element.

The toTable function work for 2 elements, but I can't get the correct type for the toTableGeneric function.

Is it possible in Typescript 4.5 ?

interface MyItem {
    stringValue: string;
    booleanValue: boolean;
}

interface Column<Item, Value> {
    getter: (row: Item) => Value;
    setter: (row: Item, value: Value) => void;
}

export const toTable = <C1Type extends unknown, C2Type extends unknown>(
    items: [Column<MyItem, C1Type>, Column<MyItem, C2Type>]
) => items;

export const toTableGeneric = <Columns extends Column<MyItem, unknown>[]>(items: [...Columns]) => items;

export const table = toTableGeneric([
    {
        getter: (row: MyItem) => row.stringValue,
        setter: (row, value) => {
            row.stringValue = value;
        },
    },
    {
        getter: (row: MyItem) => row.booleanValue,
        setter: (row, value) => {
            row.booleanValue = value;
        },
    },
]);
0

There are 0 best solutions below