I am coding a function that gets data based on a form and uses the form available from AntDesign but when I use it with Vue 3 and TypeScript it gives an error message as:
const formRef: Ref<FormInstance | undefined>
'formRef.value' is possibly 'undefined'.ts(18048)
And here are my related code snippets:
template:
<a-form
ref="formRef"
:model="DataCreate"
name="form_in_modal"
:validate-messages="validateMessages"
>
<a-form-item
:name="['new', 's3Account']"
label="s3Account"
:rules="[{ required: true }]"
></a-form-item>
...
</a-form>
Script:
import { ref, h, computed, onMounted, reactive, toRaw } from "vue";
import type { FormInstance } from "ant-design-vue";
const formRef = ref<FormInstance>()
const visibleCreate = ref<boolean>(false)
const CreateConfig = async () => {
formRef.value.validateFields().then(values => { //Error here
console.log('Received values of form: ', values);
console.log('formState: ', toRaw(DataCreate));
visibleCreate.value = false;
formRef.value.resetFields(); //Error here
console.log('reset formState: ', toRaw(DataCreate));
}).catch(info => {
console.log('Validate Failed:', info);
});
};
I'm having trouble starting to use TypeScript, hope to get some help from you guys. Thanks very much
CodePudding user response:
That's because you didn't give it a default value upon construction, therefore its type is "extended" to also include undefined
which is the default value when none is provided.
If this is the desired way of initializing it, you can use the assertion chaining myRef!.value
(this says to typescript "Although the type says it can be null or undefined, it won't, or if it does let it fail).
Otherwise you can also use optional chaining myRef?.value
(this says to typescript to only call the method if the value is neither null
nor undefined
).