ChrisK
ChrisK

Reputation: 33

Vue 3 - Composition Api - Typescript -> type of emit

I'm starting with VUE 3 and the composition api using Typescript for the first time. I have the setup method like the following: setup(props: { widgetType: string; displayType: string; trigger: number }, { emit }) Now, when I'm building this file, I get the error "Binding element 'emit' implicitly has an 'any' type.". I do not know how to fix this. I tried different solutions from the web but nothing worked. Can anybody help me? Regards Chris

Upvotes: 3

Views: 7380

Answers (2)

Denis Grushak
Denis Grushak

Reputation: 380

For example correct typing with component "App" and composable "useModal"

App:

<script lang="ts"> 
 import {defineComponent, SetupContext, ComponentPropsOptions} from 'vue';
 import {useModal} from '@/composable/useModal';
                    
 export default defineComponent({
   name: 'App',
   emits: ['openModal'],
   setup(props: ComponentPropsOptions, {emit}: SetupContext) {
     const openModal = useModal({emit});
                    
     return {openModal};
   }
});
</script>

useModal:

import {SetupContext} from 'vue';

interface UseModalProps {
  emit: SetupContext['emit'];
}

export function useModal({emit}: UseModalProps) {
  function openModal({title, type}: {title: string; type: string}): void {
    emit('openModal', {title, type});
  }

  return {openModal};
}

Upvotes: 1

David Ritchie
David Ritchie

Reputation: 546

You need to define your component with the defineComponent method and apply the correct type to props. If you are using single file components it would look something like this

<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
    props: {
        widgetType: {
            type: String,
            required: true
        },
        displayType: {
            type: String,
            required: true
        },
        trigger: {
            type: number,
            required: true
        }
    },

    setup(props, { emit }) {

        // Rest of your setup code here
    }
});
</script>

Upvotes: 2

Related Questions