Answer the question
In order to leave comments, you need to log in
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];
}
prop: keyof T
and else T[K]: number
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',
},
];
'number'
and 'alsoNumber',
could be passed in this case. Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question