vue-maybe-undefined
The template reads a field or index of a value that may be undefined (x.name, x[0]), and no v-if, &&, ? : or ?. around the read checks it.
Why: the template isn't type-checked unless you run vue-tsc. {{ user.name }} with an empty user compiles, then throws on the first render, and the component doesn't show at all. Guide: Vue.
Values that may be undefined:
- a
ref()orshallowRef()made without a value (or withundefined), or whose type allowsundefinedornull; - an optional prop (
user?: User) without a default; defineModel()withoutrequired: trueor adefault;inject(key)without a default.
✕ Rejectedvue-maybe-undefined
vue
<script setup lang="ts">
import { ref } from "vue";
const selected = ref<{ name: string }>();
</script>
<template>
<p>Selected: {{ selected.name }}</p>
</template>✅ Accepted: check it first
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { ref } from "vue";
const selected = ref<{ name: string }>();
</script>
<template>
<p v-if="selected">Selected: {{ selected.name }}</p>
<p v-else>Nothing selected</p>
</template>✅ Accepted: give it a default
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
const { label = "Save" } = defineProps<{ label?: string }>();
</script>
<template>
<button>{{ label.toUpperCase() }}</button>
</template>The quick fix writes ?. (selected?.name), which shows nothing while the value is missing. If the value is data being loaded, keep it in an AsyncState instead (vue-ref-without-value), and show it with <Match>.
The checks it understands: v-if="x", v-if="x !== undefined" (and != null), v-else after v-if="!x", x && x.name, x ? x.name : "", and a check of a longer path (v-if="x.tag === 'A'" means x is there). Through ?. too, as TypeScript reads it: a truthy x?.ready means x is there (v-if="x?.ready && x.items.length > 0"), and so does x?.index === i when i can't be undefined. Each v-else-if and v-else of a chain knows what the conditions before it ruled out.
✅ Accepted: checked through ?.
✓ Accepted0 diagnostics
vue
<script setup lang="ts">
import { ref } from "vue";
type Menu = { readonly index: number; readonly label: string };
const open = ref<Menu>();
</script>
<template>
<p v-for="index in [0, 1, 2]" :key="index">
<span v-if="open?.index === index">{{ open.label }}</span>
</p>
</template>The checker has no types, so "can't be undefined" means: a literal, arithmetic, a v-for name, or a binding it doesn't know to be possibly undefined. x?.index === other where other is a ref() without a value is still reported. Only the template is checked: in the script, TypeScript already makes you check.