I am trying to write my own wrapper for vuetify components, so I don't have to define the same props in every component. E.g. I want to create my own TextField, that has defaultProps, but can also accept all props, that would normally go to VTextField.
I was defining the script setup section like this:
<script lang="ts" setup>
import type { ExtractPropTypes } from 'vue';
import { computed } from 'vue';
import { VTextField } from 'vuetify/components';
type VTextProps = InstanceType<typeof VTextField>['$props'];
// type VTextProps = ExtractPropTypes<typeof VTextField>;
const props = defineProps<VTextProps>();
const emit = defineEmits(['update:modelValue']);
const value = computed({
get() {
return props.modelValue;
},
set(value) {
emit('update:modelValue', value);
},
});
</script>
I tried two different versions of extracting the props of VTextField:
type VTextProps = InstanceType<typeof VTextField>['$props'];
type VTextProps = ExtractPropTypes<typeof VTextField>;
But I cannot get both of them to work. In my IDE it seems to function, also the autocomplete works, however vite is throwing the following error:
[vite] Internal server error: [@vue/compiler-sfc] Unresolvable type reference or unsupported built-in utility type
I feel like, the defineProps function of vue cannot correctly parse this utility type. What would be your suggestion for a workaround for this, so I don't have to define my own types? It seems vuetify does not export its types...
Any idea or help is highly appreciated!
I don't think current Vue (3.4) can use an extracted type to generated props. In the IDE, it will look like it is working, since the IDE does full type analysis, but then the component won't compile.
In the documentation on composition API with TypeScript, there is a section on syntax limitations that says:
However, Vuetify 3 components all build their props through a factory function (see code). You can import the function and use it to generate a props object for
defineProps(). Ironically, the factory function is not typed, so you still need to use the extracted type if you want autocomplete and type hints in your IDE:If you want to extend the props object, you can use the props factory function from Vuetify directly. But since you cannot use local variables in
defineProps(), and you have to supply TS types manually, I would not use it directly indefineProps(), but rather a function that supplies types, too. Something like:Then you can use it like this:
Not sure how practicable this is, but there you go.