Home > OS >  TypeScript - extract nested property from all properties in object
TypeScript - extract nested property from all properties in object

Time:06-14

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?

CodePudding user response:

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']
};
  • Related