Skip to content

Add ability to define required nullable props #3948

Closed
@aantipov

Description

@aantipov

What problem does this feature solve?

I haven't found a way to properly define required nullable props.

Why

I want to be able to define a component property that is required and accepts null as a value (along with "normal" types like String, Number, etc.)

I consider null as a value, which indicates an absence of a value.
undefined means the value is unknown (e.g. we don't know it yet because we haven't got a response from API request).
Hence, null and undefined should not be treated the same.

Problems with current workarounds

1. Marking the property as optional.

  1. If there is a bug in the code and a parent component does not specify the property at all, then I won't get any warnings from Vue.
  2. If there is a bug in the code and a parent component provides undefined as a value, then I won't get any warnings from Vue.
  3. Typescript complains about the following code
props: {
  category: {
    type: String,
    required: false,
  }
},
setup(props) {
  const { category } = toRefs(props);
  console.log(category.value)

because TS considers category as possibly 'undefined'
image (1)

2. Mark the prop as required and hint TS about possible values

props: {
  category: {
    type: String as () => string | null,
    required: true,
  }
}

I get Vue warnings in the console "[Vue warn]: Invalid prop: type check failed for prop “category”. Expected String with value “null”, got Null"

What does the proposed API look like?

I have 2 ideas:

  1. Adding null to the list of possible type values https://v3.vuejs.org/guide/component-props.html#type-checks

So that I can define the prop the following way:

props: {
  category: {
    type: [String, null],
    required: true,
  }
}
  1. Adding nullable option to the prop object (https://v3.vuejs.org/api/options-data.html#props):
props: {
  category: {
    type: String,
    required: true,
    nullable: true,
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    ✨ feature requestNew feature or requesthas workaroundA workaround has been found to avoid the problemneed guidanceThe approach/solution in the PR is unclear and requires guidance from maintainer to proceed further.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions