0

Given an object that has several properties. Each property (bla, foo, third) has 2 sub-properties: initialValue and actions. The actions sub-property has different value each time, like that:

const myContainer = {
    bla: {
        initialValue: 1,
        actions: { 
            clear: () => {},
            increase: () => {}
        }
    },
    foo: {
        initialValue: 'FOO',
        actions: {
            foo: () => {}
        }
    },
    third: {
        initialValue: 133,
        actions: {
            doNothing: () => {}
        }
    }
};

I would like to get a type with only the actions sub-property but typed, which looks like that:

type MyActions = {
    bla: {
        clear: () => {},
        increase: () => {}
    },
    foo: {
        foo: () => {}
    },
    third: {
        doNothing: () => {}        
    }
};

How can it be done?

1 Answer 1

2

It's a pretty simple mapped type, just access the ['actions'] in the value section.

type MyContainer = typeof myContainer;
type MyActions = {
    [T in keyof MyContainer]: MyContainer[T]['actions']
};
Sign up to request clarification or add additional context in comments.

2 Comments

What is the best way to extract these values, not just type?
const actions = Object.fromEntries(Object.entries(myContainer).map(([key, val]) => [key, val.actions]))?

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.