Jiří ProcházkaArticles

Jiří Procházka Articles

VueNuxt#frontend

Passing null to props in Vue (with Typescript)

3 months ago - 5 min read #vue

As I'm going through numerous forums and reddit, I see this as a pretty common question:

How to pass null to props?

Props

Props are the main way how to pass data to child components.

// MyComponent.vue
<script setup lang="ts">
defineProps({
  value: {
    type: String
  }
})
</script>
<template>
  <div>
    {{ value }}
  </div>
</template>

Usage:

// this will render <div>Hello World!</div>
<MyComponent value="Hello World" />

As the prop is not marked as required: true, you can pass nothing there and it will be still a valid scenario here - the prop will be undefined and no text will be rendered.

But null? No, it is not nor string nor undefined so it is not a valid value here.

Passing null to prop

When you need to pass null to the prop, the first - and to be honest a logic - thing would be:

<script setup lang="ts">
defineProps({
  value: {
    type: [String, Null]
  }
})
</script>

But it is not working that way! - don't ask me why..

The correct way

<script setup lang="ts">
defineProps({
  value: {
    type: null as unknown as PropType<string | null>,
    default: null,
    required: false
  }
})
</script>

That's it..

Well, it's a bit weird way how to define a prop accepting a null, but it is working and compiler is not complaining.

Jiří Procházka Newsletter

Want to get new tips for Vue & Nuxt?