简体   繁体   中英

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

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
    };
  }
})

在此处输入图像描述


在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM