'Generate empty object based on reactively interface
I have interface that is generated base on enum and it has readonly keys
enum HealthPlanStatus {
InProgress = 'InProgress',
Completed = 'Completed',
}
export type THealthPlanCardsByStatus = {
[status in keyof typeof HealthPlanStatus]: {
cards: string[];
};
}
In my project I want to correctly declare an empty object that is generated by HealthPlanStatus.
const cards = ['1', '2', '3']
const cardsGroupedByStatus: any = {}
Object.values(HealthPlanStatus).forEach(status => {
cardsGroupedByStatus[status] = cards.filter(card => card)
})
To avoid errors it has now "any", but I want to see any of this variants:
- const cardsGroupedByStatus: THealthPlanCardsByStatus = {}
- const cardsGroupedByStatus = {} as THealthPlanCardsByStatus
In both cases I have different errors:
- const cardsGroupedByStatus: THealthPlanCardsByStatus Type '{}' is missing the following properties from type 'THealthPlanCardsByStatus': InProgress, Completed
- Cannot assign to 'InProgress' / 'Completed' because it is a read-only
If it's not possible, please, give me advise how to correctly make declaration for new generates object. Thanks!
Solution 1:[1]
Based on comments:
- You don't need
keyof typeof, remove it and leave just:
export type THealthPlanCardsByStatus = {
[status in HealthPlanStatus]: {
cards: string[];
};
}
- Then you can use
const cardsGroupedByStatus = {} as THealthPlanCardsByStatus
Object.values(HealthPlanStatus).forEach(status => {
cardsGroupedByStatus[status] = { // you forgot initialize object here
cards: cards.filter(card => card)
}
})
or
const cardsGroupedByStatus: Partial<THealthPlanCardsByStatus> = {}
Object.values(HealthPlanStatus).forEach(status => {
cardsGroupedByStatus[status] = {
cards: cards.filter(card => card)
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Фарид Ðхмедов |
