Skip to content

Reactive Props Destructure | Typescript | Boolean Optional Default True - Doesn't work, still showing false #14093

@kcfdaniel-westjet

Description

@kcfdaniel-westjet

Vue version

3.5.24

Link to minimal reproduction

https://play.vuejs.org/#eNp9kstOwzAQRX9l5A2thBKem5IWAWIBEg8BS0sopJM04NiWH6Uoyr8ztiGAhLpJ4jt3JsfX7tmZ1tnaI5uxwlam1Q4sOq9BlLKZc+YsZwsu204r46AHJW+Ulw6XMEBtVAc71LxzwiV5SDZ1WSHcG6Ut9FwCdB/nSonTGbzQC0tJziDe+o406bsXNCQNob9S0jrQsXcOS6xbiXFSEZ+LyTT+Jtn6r8nkdMbjbppJq/29PUKbpzmxYUSeTKYwXySuMIWAMqGaSZo0PYE8B7tS7xbqUlgkrCmXRZ5ioRBo4bDTonRIK4Bitb/oR5BhKHIS/hQC0qgX+a9utkvREkTdNtmrVZLyj1ycVarTrUBzp11LkJzNEnGolUKo9+uoxV1/69UKq7d/9Fe7CRpn9wYtmjVyNtZcaRp0qXz5eIsb+h6LnVp6Qe4txQekAH1gTLZzL5eE/csXaa/izWll82QvNw6l/d5UAA3OIfo5o3t0sWXrP7iH2VHso/OhFJ/XaMJMCvAwO84OjtjwCbmX8is=

Steps to reproduce

Child.vue

<script setup lang="ts">
import { onMounted } from 'vue';

interface Props {
  myBool?: boolean;
}

const props = defineProps<Props>();

const { myBool = true } = props;

onMounted(() => {
  console.log(myBool); // shows false
})
</script>

Parent.vue

<template>
  <Child/>
</template>

<script setup lang="ts">
import Child from "./Child.vue";

What is expected?

Inside the onMounted hook, myBool should be true

What is actually happening?

Inside the onMounted hook, myBool is false

System Info

Any additional comments?

With typescript, this way of providing default value is nice: const { myBool = true } = props;. But for optional boolean that I want to default to true, this way of providing default value doesn't work. Do we really need to fallback to withDefaults and do something like this if we also want reactive props destructuring?

Child.vue

<script setup lang="ts">
import { ref, onMounted } from 'vue';

interface Props {
  myBool?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  myBool: true,
});

const { myBool } = props;

onMounted(() => {
  console.log(myBool); // shows true
})
</script>

The fact that giving default values to other types like const { myNum = 0 } = props; works, but const { myBool = true } = props; doesn't, kinda makes this syntax something I wouldn't recommend. I think either there should be a way that consistently provides default values like this, or just don't recommend this, and say that we should use withDefaults instead.

https://vuejs.org/api/sfc-script-setup.html#default-props-values-when-using-type-declaration

In the current state, I would modify this part and say use withDefaults even for vue 3.5+, don't declare default values simply with Reactive Props Destructure.
Image

In the long run, I would hope const { myBool = true } = props; to work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions