Subscribe on changes!

TS2345 error occurs when using nested objects withDefaults

avatar
Dec 16th 2021

Version

3.2.26

Reproduction link

gist.github.com

Steps to reproduce

I am specifying a nested object in the component props, and if I specify a default value for props, I get a Type error.

interface ISampleProps {
  foo: {
    bar: string
  }
}
const defaultValue: ISampleProps = {
  foo: {
    bar: 'bar'
  }
};
const props = withDefaults(defineProps<ISampleProps>(), defaultValue);

What is expected?

Expect the 'bar' string to be the default value for the foo.bar object in props

What is actually happening?

TS2345: Argument of type 'ISampleProps' is not assignable to parameter of type 'InferDefaults<Readonly<ISampleProps>>'.   Types of property 'foo' are incompatible.   

Type '{ bar: string; }' is not assignable to type '(props: Readonly<ISampleProps>) => { bar: string; }'.       

Type '{ bar: string; }' provides no match for the signature '(props: Readonly<ISampleProps>): { bar: string; }'.
avatar
Dec 16th 2021

Try this:

interface ISampleProps {
  foo: {
    bar: string
  }
}

const props = withDefaults(defineProps<ISampleProps>(), {
  foo: () => {
    return {
      bar: '123'
    }
  }
})
avatar
Dec 16th 2021

Or even passing Partial<ISampleProps> for optional props.