Exploring the use of TypeScript in a Nuxt3 project for the first time has been quite an experience.
One specific component in the project is focused on either creating or editing a person in the backend:
<template>
<UCard>
<template #header>
<h3 class="font-semibold text-xl">
{{
props.mode === "create"
? "Ajouter une personne"
: "Modifier une personne"
}}
</h3>
</template>
<UForm :schema="schema" :state="state" class="space-y-2" @submit="onSubmit">
<UFormGroup class="" label="Prénom" name="firstName">
<UInput v-model="state.firstName" :disabled="props.mode === 'update'" />
</UFormGroup>
<UFormGroup class="" label="Nom" name="lastName">
<UInput v-model="state.lastName" :disabled="props.mode === 'update'" />
</UFormGroup>
<UFormGroup class="" label="Email" name="email">
<UInput v-model="state.email" />
</UFormGroup>
<UFormGroup class="" label="Téléphone" name="phone">
<UInput v-model="state.phone" />
</UFormGroup>
// More form fields here...
</UForm>
<template #footer> </template>
</UCard>
</template>
<script setup lang="ts">
// TypeScript logic here...
const props = defineProps({
mode: String,
person: { type: Object as () => IPerson },
});
// More TypeScript logic...
if (props.mode === "update") {
state.id = props.person.id;
state.firstName = props.person.firstName;
state.lastName = props.person.lastName;
state.email = props.person.email;
state.phone = props.person.phone;
state.memberSince = props.person.memberSince.substring(0, 10);
state.memberLastYear = props.person.memberLastYear;
}
async function onSubmit(event: FormSubmitEvent<any>) {
// onSubmit function logic...
}
</script>
Here's the structure of the IPerson
interface:
export interface IPerson {
// IPerson interface properties...
};
Before integrating the
typescript: {
typeCheck: true
}
into the nuxt.config.ts
, everything ran smoothly.
However, upon adding the typeCheck: true
, compilation yielded 9 errors, all revolving around the same issue:
ERROR(vue-tsc) 'props.person' is possibly 'undefined'.
Most of these errors stem from sections where props.person
is used, particularly in this block of code:
if (props.mode === "update") {
state.id = props.person.id;
state.firstName = props.person.firstName;
state.lastName = props.person.lastName;
state.email = props.person.email;
state.phone = props.person.phone;
state.memberSince = props.person.memberSince.substring(0, 10);
state.memberLastYear = props.person.memberLastYear;
}
After hours of searching online for a solution to this persistent issue, assistance is greatly needed.