V
V
Vadim2021-04-03 12:09:51
typescript
Vadim, 2021-04-03 12:09:51

How to pass a generic function argument key of type keyof T and at the same time have T[key]: number?

There is a function:

function mkSorter<T extends { [key: string]: unknown }>(prop: keyof T) {
  return (a: T, b: T) => a[prop] - b[prop];
}


How to add another constraint so that you can only pass such a prop, where prop: keyof Tand else T[K]: number

To use like this:

type SomeObjectType = {
  number: number;
  alsoNumber: number;
  string: string;
  anotherString: string;
  bool: boolean;
};

const columns: ColumnsType<SomeObjectType> = [
  {
    title: 'Also number',
    dataIndex: 'alsoNumber',
    sorter: mkSorter<SomeObjectType>('alsoNumber'),
    defaultSortOrder: 'descend',
  },
];


And no values ​​other than 'number'and 'alsoNumber',could be passed in this case.

The current non-working variant.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-04-03
@bingo347

type ChooseKeys<O, T> = {
    [K in keyof O]: O[K] extends T ? K : never;
}[keyof O];

// 'number' | 'alsoNumber'
type Test1 = ChooseKeys<{
  number: number;
  alsoNumber: number;
  string: string;
  anotherString: string;
  bool: boolean;
}, number>;

// 'number' | 'alsoNumber' | 'bool'
type Test2 = ChooseKeys<{
  number: number;
  alsoNumber: number;
  string: string;
  anotherString: string;
  bool: boolean;
}, number | boolean>;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question