简体   繁体   English

为 vue3 setup() arguments 正确的 typeScript 类型

[英]Correct typeScript Type for vue3 setup() arguments

I'm using vue3 with typescript, and I'm using composition API.我正在使用带有 typescript 的 vue3,并且我正在使用组合 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.我知道这可以通过制作任何类型的propscontext来解决,但这会破坏 TypeScript 的目的。

VS Code intellisense showing me the following type, but I'm not able to find the module from these type are exported. VS Code intellisense 向我展示了以下类型,但我无法从这些类型中找到导出的模块。

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

What is the correct Type for the setup function, and from where it is exported?. setup function 的正确类型是什么,以及从哪里导出?

The props can not be inferred because you forget to use defineComponent method to create your component.无法推断道具,因为您忘记使用defineComponent方法来创建组件。 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.要解决此问题并让Vue的道具成为红外线,您需要包装您在defineComponent方法中导出的整个 object。

More about defineComponent更多关于defineComponent

The <script lang="ts"> part of example Vue 3 composition API component should look like that:示例 Vue 3 组合 API 组件的<script lang="ts">部分应如下所示:

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> ).对于更复杂的类型,例如接口,您需要使用Object as PropType<T>Object as PropType<IconProps> )。 More about PropType<T>更多关于PropType<T>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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