skip to Main Content

I am creating a complex table configuration type, where I would like to infer the type of a value based on an accessor key.

The column configuration type looks like

type ColumnConfig<Row,Acc extends keyof Row = keyof row> = {
  accessor: Acc;
  render: React.FC<{value: Reducer<A, Row>}>;
}

The above works absolutely fine when both args are passed:

const foo: ColumnConfig<{foo: 'bar'}, 'bar'> = {
 accessor: 'bar',
 render: ({value}) => <></> // Value type hint is 'bar'
}

However, I don’t always want to pass in the generic arg, as I would like to infer it.

const foo: ColumnConfig<{foo: 'bar'}> = {
 accessor: 'bar',
 render: ({value}) => <></> // Value type hint is keyof {foo: 'bar'}
}

It feels like typescript is refusing to infer the type whenever I pass any of the generic args. Is there a good way to get around this?

I have tried moving things around but I can’t get away without passing the Row type here, else I lose type hinting in the accessor field.

2

Answers


  1. Perhaps, a mapped type should be fine for your case: TS Playground

    It will let TypeScript infer the type of value directly from accessor

    type ColumnConfig<Row> = {
      [K in keyof Row]: {
        accessor: K;
        render: (value: Row[K]) => void;
      };
    }[keyof Row];
    
    Login or Signup to reply.
  2. This is what you need, I guess

    type ColumnConfig<Row,Acc extends keyof Row = keyof Row> = {
      accessor: Acc;
      render: React.FC<{value: Row[Acc]}>;
    }
    
    const foo: ColumnConfig<{foo: 'bar'}> = {
      accessor: 'foo',
      render: ({value}) => <></> // Value type hint is 'bar'
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search