what is the best way to type such a nested object? I know that each object can simply be registered separately, but this option is not the best
const dateButtons = {
1: {
id: 1,
title: 'All',
sortBy: { date: 'DD MMM YYYY', time: true },
},
2: {
id: 2,
title: '11 10 2022',
sortBy: { date: 'DD MM YYYY' },
},
3: {
id: 3,
title: '20:11 11.10.2022',
sortBy: { date: 'DD.MM.YYYY', time: true },
},
4: {
id: 4,
title: '11-10-2022',
sortBy: { date: 'DD-MM-YYYY' },
},
5: {
id: 5,
title: '11 oct Thu',
sortBy: { date: 'Do MMM dddd' },
},
};
if it was an array, then I would just write
type myButtons = {
id: number;
title: string;
sortBy: { date: string; time?: boolean };
}[];
CodePudding user response:
You can do this:
interface ButtonData {
id: number;
title: string;
sortBy: { date: string; time?: boolean };
}
type DateButtons = { [key in number]: ButtonData }
const dateButtons: DateButtons = {
// ..
}
to specify that each key in your object is a number and each value is a ButtonData
.