I built a Generic Type for sort options. Now I am left with two alternatives, which both seem right.
// Option 1
export type SortSearchBy<DtoType> = Record<keyof Partial<Omit<DtoType, 'orderByFields'>>, SortBy>
// Option 2
export type SortSearchBy2<DtoType> = {
[x in keyof Partial<Omit<DtoType, 'orderByFields'>>]: SortBy
}
However the fields of DtoType are only optional in the second option. For the first option, all fields of DtoType (execpt for orderByOption) have to be filled:
class AnimalDto {
name: string
age: number
orderByFields: SortSearchBy<AnimalDto>
}
// here you can('t) set
orderByOptions = {
name: {
option: 'ASC',
order: 1
},
// Error: Type is missing the following properties... (age)
}
class PersonDto {
name: string
age: number
orderByFields: SortSearchBy2<PersonDto> // Notice the 2
}
// while here it is possible
orderByFields = {
name: {
option: 'ASC',
order: 1
}
// No Error
}
Why does this behave differently, when I have used the Partial generic for both types.