One of my Interfaces has the following structure:
export enum SortValueType {
String = 'string',
Number = 'number',
Date = 'date',
}
export interface SortConfig {
key: string;
direction: SortDirection;
type: SortValueType;
options?: {
sortBy?: 'year' | 'day';
};
}
I want to enhance this Interface by restricting the possible values of options.sortBy
based on the value of type
. I am designing functions that rely on the type
property, so it should not be allowed to have a scenario where type
is string
and options.sortBy
is set to year
.
Below is the implementation of the getIteratee
function:
private getIteratee(config: SortConfig) {
if (config.type === SortValueType.String) {
return item => _lowerCase(item[config.key]);
}
if (config.type === SortValueType.Date) {
const sortBy = _get(config, 'options.sortBy') as 'year' | 'day';
if (!!sortBy && sortBy === 'year') {
return item =>
!!item[config.key]
? new Date(item[config.key]).getFullYear()
: undefined;
}
if (!!sortBy && sortBy === 'day') {
return item =>
!!item[config.key]
? new Date(item[config.key].toJSON().split('T')[0])
: undefined;
}
}
return config.key;
}
I am also open to exploring more versatile solutions.