Home > Enterprise >  Large Nested Defaults in TypeScript?
Large Nested Defaults in TypeScript?

Time:06-21

I have code similar to the following:

export type Bar = {
    baz: number
};

export type FooConstructorArguments = {
    config: Bar
};

class Foo {
    construction({
        config: {
            baz = 1
        }
    }: FooConstructorArguments) {
        let c = config;
        let b = baz;
    }
}

But neither config nor baz are accessible. What is the proper way to utilize nested typed argument defaults within TypeScript?

CodePudding user response:

baz is accessible. config isn't because it's just part of the destructuring path to baz, not a target of the destructuring pattern. If you want both config and baz, you'll need to just pick out config in the parameter list, then pick baz from it after:

class Foo {
    construction({ config }: FooConstructorArguments) {
        const { baz = 1} = config;
        let c = config;
        let b = baz;
    }
}

Playground link

or if you don't really need baz and just need b:

class Foo {
    construction({ config }: FooConstructorArguments) {
        let c = config;
        let b = config.baz ?? 1;
    }
}

Playground link


Side note: I've left construction in the above in case it's meant to be a method, but suspect you meant constructor.

  • Related