6

I'm using vue3 with typescript, and I'm using composition API.

export default {
    setup(props, context) {
    },
};

This throws an error as follows

Failed to compile.

src/components/LoginForm.vue:20:11
TS7006: Parameter 'props' implicitly has an 'any' type.
    18 |
    19 | export default {
  > 20 |     setup(props, context) {
       |           ^^^^^

I know this can be fixed by making props, context of type any, but that will defeat the purpose of TypeScript.

VS Code intellisense showing me the following type, but I'm not able to find the module from these type are exported.

setup?: ((this: void, props: {}, ctx: SetupContext<EmitsOptions>) => void | RenderFunction

What is the correct Type for the setup function, and from where it is exported ?.

1
  • Type of props should be inferred automatically from your component's props option... Commented Apr 3, 2021 at 7:57

1 Answer 1

12

The props can not be inferred because you forget to use defineComponent method to create your component. To resolve this issue and let props to be infrared by Vue you need to wrap your whole object which you are exporting in defineComponent method.

More about defineComponent

The <script lang="ts"> part of example Vue 3 composition API component should look like that:

export default defineComponent({
  name: "PersonComponent",
  props: {
    firstName: {
      type: String,
      required: true
    },
    lastName: {
      type: String,
      required: true
    },
    age: {
      type: Number,
      required: true
    }
  },
    setup(props) {
    const firstName = props.firstName;
    const lastName = props.lastName;
    const age = props.age;
    return {
      firstName,
      lastName,
      age
    };
  }
})

enter image description here


enter image description here

For more complexd types such as interfaces you need to use Object as PropType<T> (Object as PropType<IconProps>). More about PropType<T>

Sign up to request clarification or add additional context in comments.

3 Comments

I thought defineComponent was for using composition API within Vue v2?
@Emobe I it part of Vue3. Please take a look at this link to Vue 3 documentation: defineComponent which I added in my answer
Yeah you're right, I noticed it was in there right after I commented. Nice to know it's in there :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.