docs icon indicating copy to clipboard operation
docs copied to clipboard

Add info for wrapping refrence types in functions for withDefaults

Open Topograph opened this issue 7 months ago • 1 comments

This code in typescript triggers a confusing Error:

export interface Props {
  msg?: string
  labels?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: ['one', 'two'] 
})

Type 'string[]' is not assignable to type '(props: LooseRequired<Props>) => string[]'. Type 'string[]' provides no match for the signature '(props: LooseRequired<Props>): string[]'.ts-plugin(2322) TestComp.vue(7, 3): The expected type comes from property 'labels' which is declared here on type 'InferDefaults<LooseRequired<Props>>'

Description of Problem

This is correctly circumvented in the example in the docs by wrapping the default value for "labels" in a function.

export interface Props {
  msg?: string
  labels?: string[]
}

const props = withDefaults(defineProps<Props>(), {
  msg: 'hello',
  labels: () => ['one', 'two'] // wrapped in function
})

However its not clearly explained and the error message is confusing

Proposed Solution

I feel like adding a short explanation to the docs as proposed in the pull request might clear things up.

Topograph avatar Jun 27 '24 08:06 Topograph