0

I have a normalized redux structure addressesState as below. I need to define the type of that as specified in the comments

interface iAddressItem {
    firstName: string;
    lastName: string;
    street: string;
}

const addressesState = {
    // key "ids" is static
    // value is Array<string>
    ids: ["1345", "1346"],

    // typeof key is string and it is dynamic
    // typeof value is iAddressItem
    "1345": {
        firstName: "Cinta",
        lastName: "Riardo",
        street: "Cake Street 34",
    },

    // typeof key is string and it is dynamic
    // typeof value is iAddressItem
    "1346": {
        firstName: "Nosipho",
        lastName: "Tracey",
        street: "Baker Street 42",
    },
};

I tried to define the type of addressesState as below:

type AddressesType = {
    [key in string | number]?: iAddressItem;
} & {
    ids?: Array<number>;
};

But when I'm initializing the redux state as:

const initalAddressesState: AddressesType = {
    ids: []
}

I'm getting the error:

Type '{ ids: never[]; }' is not assignable to type 'AddressesType'.
  Type '{ ids: never[]; }' is not assignable to type '{ [x: string]: iAddressItem | undefined; [x: number]: iAddressItem | undefined; }'.
    Property 'ids' is incompatible with index signature.
      Type 'never[]' is missing the following properties from type 'iAddressItem': firstName, lastName, street(2322)

Any bits of help or insights would be great

Swalah Amani
  • 1
  • 1
  • 2
  • [My research](https://stackoverflow.com/questions/49969390/how-do-i-type-an-object-with-known-and-unknown-keys-in-typescript/57993115#57993115) and a lot of fiddling lead me to the conclusion that you can't easily create objects of such types. Interestingly enough (though probably not useful to you), it does work if you change that first key type to `[key in number]?`. – Noah Dec 28 '20 at 01:44
  • ...and also with a finite type like `[key in 'addr' | 'address']`. – Noah Dec 28 '20 at 01:47
  • Wait, are the dynamic keys always numeric-like strings? If so there may be another answer by using `{ids?: string[], [k: number]: iAddressItem | undefined}` where the index signature is `number`. Does that work for you? If so please edit the question to specify this, and I'll vote to reopen. – jcalz Dec 28 '20 at 02:41
  • In any case, see [this code](https://tsplay.dev/DWK6Dm) for the numeric index signature solution, as well as the answer to the other question translated to this use case. – jcalz Dec 28 '20 at 02:48

0 Answers0