1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.