B45i
B45i

Reputation: 2601

Correct typeScript Type for vue3 setup() arguments

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 ?.

Upvotes: 6

Views: 3807

Answers (1)

Krzysztof Kaczyński
Krzysztof Kaczyński

Reputation: 5071

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>

Upvotes: 12

Related Questions