Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(compiler-sfc): enable reactive props destructure by default #7986

Merged
merged 6 commits into from
Mar 30, 2023

Conversation

yyx990803
Copy link
Member

@yyx990803 yyx990803 commented Mar 30, 2023

Reactive props destructure was part of the Reactivity Transform proposal. The $ref part of Reactivity Transform has been dropped, but we are landing reactive props destructure as a stable feature and enabling it by default. withDefaults() is deprecated in favor of using the destructure default value syntax:

withDefaults() was marked as deprecated in this PR but the deprecation has been reverted in 4af5d1b.

<script setup lang="ts">
const { foo = 1, bar = 'ok' } = defineProps<{ foo?: number, bar?: string }>()
</script>

<template>{{ foo }} {{ bar }}</template>
  • One side benefit of this is that usage of props in the <script> block will be consistent with usage in <template>.
  • Assignment to destructured prop bindings will be compile-time error, even if the declaration is using let.
  • Calling watch() directly on a destructured prop is expected to be a common gotcha, so this is detected and will result a compile-time error that nudges the user to use a getter instead.

Caveat

You cannot enforce the type of the destructure default value in TypeScript, so technically this is possible:

<script setup lang="ts">
const { foo = 'hello' } = defineProps<{ foo?: number }>()
</script>

The resulting type of foo will be number | 'hello', i.e. the user could widen the type of the prop by mistake. That said, in most cases, this should be caught by code that expects the original type of the prop.

To address this, we perform compile-time check to catch the most common cases of type mismatch (cf9ebaf). This check is limited to cases where both the default value type and the declared type can be safely inferred. It's not comprehensive, but should provide a good enough safeguard for the most common cases.

- Reactive props destructure is now stable
- Split props destructure logic from reactivity transform package and
  move back into compiler-sfc
@yyx990803 yyx990803 changed the title feat(compiler-sfc): enable reactive props destructure by default & deprecate withDefaults() feat(compiler-sfc): enable reactive props destructure by default Mar 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant