'Correctly declare interface or type for functions params

How to correctly declare type for param cardsByStatus inside function addCardsToStatus? It works for cardsByStatus: any, but it doesn't make sense for me.

Error: Property 'map' does not exist on type '{ cards: number[]; }'

Link for live example

enum HealthPlanStatus {
    InProgress = 'InProgress',
    Completed = 'Completed',
}
type ICardsByStatus = {
    [status in HealthPlanStatus]:{
        cards: number[]
    }
}
interface IOptions {
    optionsStatus: string
}

function addCardsToStatus(cardsByStatus: ICardsByStatus, options: IOptions) {
    const {optionsStatus}: IOptions = options

    cardsByStatus[optionsStatus].map((card:number) => card)
    cardsByStatus["InProgress"].map((card:number) => card)

}

const cardsByStatus = { InProgress: { cards: [] }, Completed: { cards: [ 1, 2, 3 ] } }
const options = { optionsStatus: 'InProgress' }

addCardsToStatus(cardsByStatus, options)


Solution 1:[1]

You should first change the interface IOptions:

interface IOptions {
    optionsStatus: HealthPlanStatus
}

If optionsStatus is defined as string, it is not allowed to use it to index on object of type ICardsByStatus.

You also defined ICardByStatus to have an additional key { cards: number[] }. To access the array, you should use this key.

cardsByStatus[optionsStatus].cards.map((card:number) => card)
cardsByStatus["InProgress"].cards.map((card:number) => card)

And lastly TypeScript will now complain if you pass options to the method if you defined it as an object with a string inside. So we should change it to this:

const options = { optionsStatus: HealthPlanStatus.InProgress }

addCardsToStatus(cardsByStatus, options)

Playground

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 Tobias S.