Search code examples
typescriptobjectassociative-array

Can I declare typed associative array and then use it as typed by key object?


So, I have such an associative array structure:

type CellT = { name: string; value: number };
type AssociativeArrayT = {
    [key: string]: CellT[] | AssociativeArrayT;
};

const myObject: AssociativeArrayT = {
    key1: {
        subKey1: [
            { name: 'SomeName1', value: 100 },
            { name: 'SomeName2', value: 100 },
        ],
    },
    key2: [
        { name: 'SomeName3', value: 300 },
        { name: 'SomeName4', value: 400 },
    ],
};

I'd use this type (AssociativeArrayT) to check props whilst declaring new object.

The main problem is that after constant was initialized like: "myObject: AssociativeArrayT" = {...}, I can't get object properties by keys (surely, since I've described keys of AssociativeArrayT as string). Could you help me out, maybe there is some easy way to get key typed object that was declared this way?


Solution

  • This is what satisfies does. See docs: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html

    Rather than setting the type of your value, say this value satisfies AssociativeArrayT which means that a more specific subtype may be inferred.

    So:

    const myObject = {
        key1: {
            subKey1: [
                { name: 'SomeName1', value: 100 },
                { name: 'SomeName2', value: 100 },
            ],
        },
        key2: [
            { name: 'SomeName3', value: 300 },
            { name: 'SomeName4', value: 400 },
        ],
    } satisfies AssociativeArrayT;
    

    Which has the types you expect:

    type Test1 = keyof typeof myObject
    // 'key1' | 'key2'
    
    type Test2 = keyof typeof myObject['key1']
    // 'subKey1'
    

    See Playground